package main

import (
	"context"
	"flag"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/go-logr/logr"
	larkcard "github.com/larksuite/oapi-sdk-go/v3/card"
	"github.com/tidbcloud/devops/entity/userbehavior"
	larkutil "github.com/tidbcloud/devops/pkg/infra/clients/larkcli/util"
	"github.com/tidbcloud/devops/pkg/infra/clients/llm_cli"
	"github.com/tidbcloud/devops/pkg/infra/clients/sendgridcli"
	"github.com/tidbcloud/devops/pkg/infra/config"
	"github.com/tidbcloud/devops/pkg/infra/utils/pointer"
	"github.com/tidbcloud/devops/pkg/service/userbehavior/gtm"
)

var (
	// Test configuration flags
	emailDomain     = flag.String("domain", "acme-ai.com", "Email domain to test enrichment")
	testEmail       = flag.String("email", os.Getenv("TEST_EMAIL"), "Email address to send test email to")
	testLarkWebhook = flag.String("lark-webhook", os.Getenv("TEST_LARK_WEBHOOK"), "Lark webhook URL")
	skipEnrichment  = flag.Bool("skip-enrichment", false, "Skip LLM enrichment and use mock data")
	skipSendEmail   = flag.Bool("skip-send-email", false, "Skip actual email sending")
	skipSendLark    = flag.Bool("skip-send-lark", false, "Skip actual Lark card sending")
	verbose         = flag.Bool("v", false, "Verbose output")
	testTenantID    = flag.Uint64("tenant-id", 12345, "Test tenant ID")
	testRegion      = flag.String("region", "NA", "Test region")
	testTenantName  = flag.String("tenant-name", "Test Company", "Test tenant name")
)

func main() {
	flag.Parse()

	fmt.Println("==============================================")
	fmt.Println("GTM Automation End-to-End Integration Test")
	fmt.Println("==============================================")
	fmt.Println()

	ctx := context.Background()
	logger := logr.Discard()

	// Check environment variables
	llmAPIKey := os.Getenv("LLM_API_KEY")
	sendGridAPIKey := os.Getenv("SENDGRID_API_KEY")

	if llmAPIKey == "" && !*skipEnrichment {
		fmt.Println("⚠️  WARNING: LLM_API_KEY not set - using mock enrichment data")
		*skipEnrichment = true
	}

	if sendGridAPIKey == "" {
		fmt.Println("⚠️  WARNING: SENDGRID_API_KEY not set - email sending will be skipped")
		*skipSendEmail = true
	}

	// Setup test configuration
	testConfig := &config.RootConfig{
		Clients: config.Clients{
			LLM: config.LLMConfig{
				GeminiKey: llmAPIKey,
			},
			SendGrid: config.SendGrid{
				APIKey: sendGridAPIKey,
			},
		},
		Services: config.Services{
			UserBehavior: config.UserBehaviorServiceConfig{
				GTM: config.GTMConfig{
					Enabled:                true,
					FromAddress:            "test@tidbcloud.com",
					EmailDelay:             6 * time.Hour,
					EmailQueueScanInterval: 5 * time.Minute,
					InternalCCList:         []string{},
					NotifyUserIDs:          []string{"343396e2", "test_user_2"},
					UseCaseProfiles: []config.UseCaseProfile{
						{
							Name:                   "ai-llm-platform",
							Description:            "AI/LLM platforms and AI infrastructure",
							CustomerReferences:     []string{"manus", "dify"},
							RequiredKeywords:       []string{"ai", "machine learning", "llm", "agent"},
							PreferredBusinessModel: "b2b",
						},
					},
				},
			},
		},
	}

	// ==============================================
	// Step 1: Company Enrichment
	// ==============================================
	fmt.Println("=== Step 1: Company Enrichment ===")
	fmt.Printf("  Email domain: %s\n", *emailDomain)

	var enrichmentText string
	if *skipEnrichment {
		enrichmentText = getMockEnrichmentData(*emailDomain)
		fmt.Println("  Using mock enrichment data")
	} else {
		// Use real enricher component
		llmCli, err := llm_cli.NewLLMCli(testConfig)
		if err != nil {
			fmt.Printf("  ❌ Failed to create LLM client: %v\n", err)
			return
		}

		enricher := gtm.NewEnricher(llmCli)
		enrichmentText, err = enricher.EnrichByEmailDomain(ctx, *emailDomain)
		if err != nil {
			fmt.Printf("  ❌ Enrichment failed: %v\n", err)
			fmt.Println("  Falling back to mock data")
			enrichmentText = getMockEnrichmentData(*emailDomain)
		} else {
			fmt.Println("  ✅ LLM enrichment completed")
		}
	}

	if *verbose {
		fmt.Printf("\nEnrichment data:\n%s\n\n", enrichmentText)
	}

	// Parse enrichment using real parser component
	enrichment, err := gtm.ParseEnrichment(enrichmentText)
	if err != nil {
		fmt.Printf("  ❌ Failed to parse enrichment: %v\n", err)
		return
	}

	fmt.Printf("  Company: %s\n", enrichment.CompanyName)
	fmt.Printf("  Vertical: %s\n", enrichment.Vertical)
	fmt.Printf("  Business Model: %s\n", enrichment.BusinessModel)
	fmt.Printf("  Confidence: %s\n\n", enrichment.ConfidenceLevel)

	// ==============================================
	// Step 2: Lead Qualification
	// ==============================================
	fmt.Println("=== Step 2: Lead Qualification ===")
	qualifier := gtm.NewSimpleQualifier(logger)
	qualified, reason := qualifier.IsQualified(enrichment)

	if qualified {
		fmt.Printf("  ✅ Lead qualified\n")
	} else {
		fmt.Printf("  ❌ Lead NOT qualified\n")
	}
	fmt.Printf("  Reason: %s\n\n", reason)

	if !qualified {
		fmt.Println("⚠️  Lead not qualified - testing standard card only")
		testStandardCard(ctx, *emailDomain, enrichmentText, *testLarkWebhook, *skipSendLark, *testTenantID, *testRegion, *testTenantName)
		return
	}

	// ==============================================
	// Step 3: Use Case Matching
	// ==============================================
	fmt.Println("=== Step 3: Use Case Matching ===")
	matcher := gtm.NewReferenceMatcher(logger, testConfig.Services.UserBehavior.GTM.UseCaseProfiles)

	contactName := "Alex Johnson"
	contactFirstName := "Alex"
	lead := &userbehavior.GTMLead{
		EmailDomain:      *emailDomain,
		Email:            fmt.Sprintf("test@%s", *emailDomain),
		ContactName:      &contactName,
		ContactFirstName: &contactFirstName,
		CompanyName:      &enrichment.CompanyName,
		Vertical:         &enrichment.Vertical,
		BusinessModel:    &enrichment.BusinessModel,
	}

	matchResult := matcher.Match(lead)
	if matchResult.Matched {
		fmt.Printf("  ✅ Use case matched: %s\n", matchResult.UseCaseProfile)
		fmt.Printf("  Customer references: %v\n", matchResult.CustomerReferences)
		lead.MatchedUseCase = &matchResult.UseCaseProfile
		lead.UseCaseMatchReason = &matchResult.Reason
	} else {
		fmt.Printf("  ❌ No use case match\n")
	}
	fmt.Printf("  Reason: %s\n\n", matchResult.Reason)

	if !matchResult.Matched {
		fmt.Println("⚠️  No use case match - testing standard card only")
		testStandardCard(ctx, *emailDomain, enrichmentText, *testLarkWebhook, *skipSendLark, *testTenantID, *testRegion, *testTenantName)
		return
	}

	// ==============================================
	// Step 4: Email Composition
	// ==============================================
	fmt.Println("=== Step 4: Email Composition ===")

	var emailContent *gtm.EmailContent
	if llmAPIKey == "" {
		fmt.Println("  ⚠️  Skipping email composition (no LLM API key)")
		emailContent = &gtm.EmailContent{
			Subject:  fmt.Sprintf("Partnership Opportunity: %s + TiDB Cloud", enrichment.CompanyName),
			HTMLBody: "<p>This is a test email from GTM automation.</p>",
		}
	} else {
		llmCli, err := llm_cli.NewLLMCli(testConfig)
		if err != nil {
			fmt.Printf("  ❌ Failed to create LLM client: %v\n\n", err)
			return
		}

		composer := gtm.NewEmailComposer(logger, llmCli)
		emailContent, err = composer.ComposeEmail(ctx, lead, matchResult)
		if err != nil {
			fmt.Printf("  ❌ Email composition failed: %v\n\n", err)
			return
		}

		fmt.Println("  ✅ Email composed successfully")
		fmt.Printf("  Subject: %s\n", emailContent.Subject)
		if *verbose {
			fmt.Printf("\n  Email body:\n%s\n", emailContent.HTMLBody)
		}
	}
	fmt.Println()

	// ==============================================
	// Step 5: Queue Email (Delayed Delivery)
	// ==============================================
	fmt.Println("=== Step 5: Queue Email (Delayed Delivery) ===")

	scheduledAt := time.Now().Add(testConfig.Services.UserBehavior.GTM.EmailDelay)
	fmt.Printf("  To: %s\n", getEmailOrDefault(*testEmail))
	fmt.Printf("  Subject: %s\n", emailContent.Subject)
	fmt.Printf("  Scheduled at: %s\n", scheduledAt.Format(time.RFC3339))
	fmt.Println()

	// ==============================================
	// Step 6: Send GTM Queued Lark Card
	// ==============================================
	fmt.Println("=== Step 6: Send GTM Queued Lark Card ===")

	if *skipSendLark {
		fmt.Println("  ⚠️  Skipped (--skip-send-lark)")
	} else if *testLarkWebhook == "" {
		fmt.Println("  ⚠️  Skipped (no --lark-webhook provided)")
	} else {
		// Build GTM queued card using production method
		queuedEmail := &userbehavior.GTMSentEmail{
			ToAddress:          getEmailOrDefault(*testEmail),
			Subject:            emailContent.Subject,
			Body:               emailContent.HTMLBody,
			UseCaseProfile:     matchResult.UseCaseProfile,
			CustomerReferences: pointer.Pointer(strings.Join(matchResult.CustomerReferences, ",")),
			ScheduledAt:        scheduledAt,
			Status:             "queued",
		}

		// Create a mock startup event to use its card building method
		event := newMockStartupEvent(*testTenantID, *emailDomain, enrichmentText, *testRegion, *testTenantName, lead, queuedEmail, testConfig.Services.UserBehavior.GTM.NotifyUserIDs)

		card, err := event.BuildCustomCard(ctx)
		if err != nil {
			fmt.Printf("  ❌ Failed to build GTM card: %v\n", err)
		} else if card == nil {
			fmt.Println("  ⚠️  No GTM card returned")
		} else {
			err := sendLarkCard(ctx, *testLarkWebhook, card)
			if err != nil {
				fmt.Printf("  ❌ Failed to send GTM card: %v\n", err)
			} else {
				fmt.Println("  ✅ GTM card sent successfully")
			}
		}
	}
	fmt.Println()

	// ==============================================
	// Step 7: Optional Dispatch (SendGrid)
	// ==============================================
	fmt.Println("=== Step 7: Optional Dispatch (SendGrid) ===")

	if *skipSendEmail {
		fmt.Println("  ⚠️  Skipped (--skip-send-email)")
	} else if *testEmail == "" {
		fmt.Println("  ⚠️  Skipped (no --email provided)")
	} else {
		sendGridCli, err := sendgridcli.NewClient(testConfig)
		if err != nil {
			fmt.Printf("  ❌ Failed to create SendGrid client: %v\n", err)
		} else {
			fmt.Printf("  Sending to: %s\n", *testEmail)
			fmt.Printf("  Subject: %s\n", emailContent.Subject)

			resp, err := sendGridCli.SendPlainEmail(ctx, sendgridcli.SendPlainEmailRequest{
				From:     testConfig.Services.UserBehavior.GTM.FromAddress,
				FromName: testConfig.Services.UserBehavior.GTM.FromName,
				To:       *testEmail,
				Subject:  emailContent.Subject,
				HTMLBody: emailContent.HTMLBody,
			})
			if err != nil {
				fmt.Printf("  ❌ Send failed: %v\n", err)
			} else {
				fmt.Println("  ✅ Email sent successfully")
				fmt.Printf("  Message ID: %s\n", resp.MessageID)
				fmt.Printf("  Status: %d\n", resp.StatusCode)
			}
		}
	}
	fmt.Println()

	// ==============================================
	// Summary
	// ==============================================
	printSummary(matchResult.Matched, *skipSendEmail, *skipSendLark, *testEmail, *testLarkWebhook)
}

func testStandardCard(ctx context.Context, emailDomain, enrichmentText, webhookURL string, skipSend bool, tenantID uint64, region, tenantName string) {
	fmt.Println("\n=== Step 4-6: Testing Standard Lark Card (Fallback) ===")

	if skipSend {
		fmt.Println("  ⚠️  Skipped (--skip-send-lark)")
	} else if webhookURL == "" {
		fmt.Println("  ⚠️  Skipped (no --lark-webhook provided)")
	} else {
		// Create a mock event without GTM data (returns nil from BuildCustomCard)
		event := newMockStartupEvent(tenantID, emailDomain, enrichmentText, region, tenantName, nil, nil, nil)

		card, err := event.BuildCustomCard(ctx)
		if err != nil {
			fmt.Printf("  ❌ Failed to build card: %v\n", err)
		} else if card != nil {
			fmt.Println("  ⚠️  Unexpected: Got custom card when expecting standard card fallback")
		} else {
			// Build standard card (simulating what DispatchUBEvents does)
			standardText := event.DefaultText(ctx)
			standardCard := buildStandardCard(standardText, "")

			err := sendLarkCard(ctx, webhookURL, standardCard)
			if err != nil {
				fmt.Printf("  ❌ Failed to send standard card: %v\n", err)
			} else {
				fmt.Println("  ✅ Standard Lark card sent successfully")
			}
		}
	}
	fmt.Println()

	fmt.Println("==============================================")
	fmt.Println("✅ End-to-End Test Complete (Standard Card)")
	fmt.Println("==============================================")
}

func printSummary(matched, skipEmail, skipLark bool, testEmail, webhookURL string) {
	fmt.Println("==============================================")
	fmt.Println("✅ End-to-End Test Complete")
	fmt.Println("==============================================")
	fmt.Println("\nTested components:")
	fmt.Println("  ✅ gtm.Enricher - Company enrichment")
	fmt.Println("  ✅ gtm.Parser - Enrichment parsing")
	fmt.Println("  ✅ gtm.SimpleQualifier - Lead qualification")
	fmt.Println("  ✅ gtm.ReferenceMatcher - Use case matching")
	if matched {
		fmt.Println("  ✅ gtm.EmailComposer - Email composition")
		if !skipEmail && testEmail != "" {
			fmt.Println("  ✅ sendgridcli.Client - Optional dispatch (SendGrid)")
		}
		if !skipLark && webhookURL != "" {
			fmt.Println("  ✅ startupUBEvent.BuildCustomCard - GTM queued card")
		}
	}

	fmt.Println("\n==============================================")
	fmt.Println("Usage Examples")
	fmt.Println("==============================================")
	fmt.Println("Basic test (mock data, no external calls):")
	fmt.Println("  go run test/test_gtm_flow.go --skip-enrichment")
	fmt.Println("")
	fmt.Println("Test with real LLM enrichment:")
	fmt.Println("  export LLM_API_KEY=your-gemini-key")
	fmt.Println("  go run test/test_gtm_flow.go --domain openai.com")
	fmt.Println("")
	fmt.Println("Full test with email sending:")
	fmt.Println("  export LLM_API_KEY=your-gemini-key")
	fmt.Println("  export SENDGRID_API_KEY=your-sendgrid-key")
	fmt.Println("  go run test/test_gtm_flow.go --domain openai.com --email your@email.com")
	fmt.Println("")
	fmt.Println("Complete test with Lark notification:")
	fmt.Println("  export LLM_API_KEY=your-gemini-key")
	fmt.Println("  export SENDGRID_API_KEY=your-sendgrid-key")
	fmt.Println("  go run test/test_gtm_flow.go \\")
	fmt.Println("    --domain openai.com \\")
	fmt.Println("    --email your@email.com \\")
	fmt.Println("    --lark-webhook 'https://open.feishu.cn/...'")
}

func getMockEnrichmentData(emailDomain string) string {
	if strings.Contains(strings.ToLower(emailDomain), "ai") ||
		strings.Contains(strings.ToLower(emailDomain), "ml") {
		return `{
  "company_name": "Acme AI Corp",
  "headquarter": "San Francisco, CA",
  "vertical": "AI/ML Platform",
  "business_model": "B2B SaaS",
  "approximate_annual_revenue": "$10M - $50M",
  "funding_series": "Series B",
  "ai_confidence_level": "high"
}`
	}

	return `{
  "company_name": "Example Corp",
  "headquarter": "New York, NY",
  "vertical": "E-commerce",
  "business_model": "B2C",
  "approximate_annual_revenue": "$5M - $10M",
  "funding_series": "Seed",
  "ai_confidence_level": "medium"
}`
}

func getEmailOrDefault(email string) string {
	if email != "" {
		return email
	}
	return "test@example.com"
}

// mockStartupEvent mimics startupUBEvent for card building (copy from production code)
type mockStartupEvent struct {
	OrgId            uint64
	tenantName       *string
	bizRegion        *string
	emailDomain      string
	extraInfo        string
	gtmLead          *userbehavior.GTMLead
	gtmSentEmail     *userbehavior.GTMSentEmail
	gtmNotifyUserIDs []string
}

func newMockStartupEvent(tenantID uint64, emailDomain, enrichmentText, region, tenantName string, lead *userbehavior.GTMLead, sentEmail *userbehavior.GTMSentEmail, notifyUserIDs []string) *mockStartupEvent {
	return &mockStartupEvent{
		OrgId:            tenantID,
		tenantName:       &tenantName,
		bizRegion:        &region,
		emailDomain:      emailDomain,
		extraInfo:        enrichmentText,
		gtmLead:          lead,
		gtmSentEmail:     sentEmail,
		gtmNotifyUserIDs: notifyUserIDs,
	}
}

func (e *mockStartupEvent) BuildCustomCard(ctx context.Context) (*larkcard.MessageCard, error) {
	// Copied from startupUBEvent.BuildCustomCard()
	if e.gtmSentEmail != nil && e.gtmLead != nil {
		return e.buildGTMResultCard()
	}

	// Otherwise use standard card (return nil for fallback)
	return nil, nil
}

func (e *mockStartupEvent) buildGTMResultCard() (*larkcard.MessageCard, error) {
	// Copied from startupUBEvent.buildGTMResultCard()
	config := larkcard.NewMessageCardConfig().
		WideScreenMode(true).
		EnableForward(true).
		UpdateMulti(false).
		Build()

	// CardUrl (same as standard card)
	cardUrl := ""
	cardLink := larkcard.NewMessageCardURL().
		Url(cardUrl).
		Build()

	header := larkcard.NewMessageCardHeader().
		Template("orange").
		Title(larkcard.NewMessageCardPlainText().
			Content("⏳ AI GTM Email Queued").
			Build()).
		Build()

	// Standard event info (same format as standard card)
	var tenantName string
	if e.tenantName != nil {
		tenantName = *e.tenantName
	}
	standardText := fmt.Sprintf("[** %s **] New non-individual tenant [**%s**](https://ops.tidbcloud.com/orgs/%d)(id: %d).\nEmail domain is %s \n\n%s",
		*e.bizRegion,
		tenantName,
		e.OrgId,
		e.OrgId,
		e.emailDomain,
		formatEnrichmentForCard(e.extraInfo),
	)

	standardDiv := larkcard.NewMessageCardDiv().
		Fields([]*larkcard.MessageCardField{
			larkcard.NewMessageCardField().
				Text(larkcard.NewMessageCardLarkMd().
					Content(standardText).
					Build()).
				IsShort(true).
				Build(),
		}).
		Build()

	// Horizontal line
	hr := larkcard.NewMessageCardHr().Build()

	// GTM processing info
	gtmInfoText := fmt.Sprintf(
		"**✅ Matched Use Case:** %s\n**📧 Email Subject:** %s\n**📬 Queued To:** %s\n**⏳ Scheduled At:** %s",
		e.gtmSentEmail.UseCaseProfile,
		e.gtmSentEmail.Subject,
		e.gtmSentEmail.ToAddress,
		e.gtmSentEmail.ScheduledAt.Format(time.RFC3339),
	)

	// Add @ mentions if configured
	if len(e.gtmNotifyUserIDs) > 0 {
		var mentions []string
		for _, userID := range e.gtmNotifyUserIDs {
			mentions = append(mentions, larkutil.AtUserInCard(userID))
		}
		gtmInfoText = gtmInfoText + "\n\n" + strings.Join(mentions, " ")
	}

	gtmInfoDiv := larkcard.NewMessageCardDiv().
		Fields([]*larkcard.MessageCardField{
			larkcard.NewMessageCardField().
				Text(larkcard.NewMessageCardLarkMd().
					Content(gtmInfoText).
					Build()).
				IsShort(false).
				Build(),
		}).
		Build()

	// Build message card
	messageCard := larkcard.NewMessageCard().
		Config(config).
		Header(header).
		Elements([]larkcard.MessageCardElement{
			standardDiv,
			hr,
			gtmInfoDiv,
		}).
		CardLink(cardLink).
		Build()

	return messageCard, nil
}

func (e *mockStartupEvent) DefaultText(ctx context.Context) string {
	// Copied from startupUBEvent.DefaultText()
	var tenantName string
	if e.tenantName != nil {
		tenantName = *e.tenantName
	}
	return fmt.Sprintf("[** %s **] New non-individual tenant [**%s**](https://ops.tidbcloud.com/orgs/%d)(id: %d).\nEmail domain is %s \n\n%s",
		*e.bizRegion,
		tenantName,
		e.OrgId,
		e.OrgId,
		e.emailDomain,
		formatEnrichmentForCard(e.extraInfo),
	)
}

// buildStandardCard builds the standard Lark card (copy from production code)
func buildStandardCard(text string, cardUrl string) *larkcard.MessageCard {
	// Copied from svc.buildCard()
	config := larkcard.NewMessageCardConfig().
		WideScreenMode(true).
		EnableForward(true).
		UpdateMulti(false).
		Build()

	cardLink := larkcard.NewMessageCardURL().
		Url(cardUrl).
		Build()

	header := larkcard.NewMessageCardHeader().
		Template("turquoise").
		Title(larkcard.NewMessageCardPlainText().
			Content("User Behavior Event").
			Build()).
		Build()

	divElement := larkcard.NewMessageCardDiv().
		Fields([]*larkcard.MessageCardField{larkcard.NewMessageCardField().
			Text(larkcard.NewMessageCardLarkMd().
				Content(text).
				Build()).
			IsShort(true).
			Build()}).
		Build()

	messageCard := larkcard.NewMessageCard().
		Config(config).
		Header(header).
		Elements([]larkcard.MessageCardElement{divElement}).
		CardLink(cardLink).
		Build()

	return messageCard
}

func sendLarkCard(ctx context.Context, webhookURL string, card *larkcard.MessageCard) error {
	// Serialize the card to JSON
	cardJSON, err := card.String()
	if err != nil {
		return fmt.Errorf("failed to serialize card: %w", err)
	}

	// Wrap in webhook format
	webhookPayload := fmt.Sprintf(`{"msg_type":"interactive","card":%s}`, cardJSON)

	req, err := http.NewRequestWithContext(ctx, "POST", webhookURL, strings.NewReader(webhookPayload))
	if err != nil {
		return fmt.Errorf("failed to create request: %w", err)
	}
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return fmt.Errorf("failed to send request: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		return fmt.Errorf("webhook returned status %d: %s", resp.StatusCode, string(body))
	}

	return nil
}

// formatEnrichmentForCard formats enrichment data for display in Lark cards
// Copied from ubevent_startup.go
func formatEnrichmentForCard(rawText string) string {
	if rawText == "" {
		return ""
	}

	// Try to parse as JSON
	enrichment, err := gtm.ParseEnrichmentJSON(rawText)
	if err != nil {
		// If JSON parsing fails, return original text (might be already formatted)
		return rawText
	}

	// Format as readable field list
	var parts []string

	if enrichment.CompanyName != "" && enrichment.CompanyName != "Unknown" {
		parts = append(parts, fmt.Sprintf("**Company Name:** %s", enrichment.CompanyName))
	}
	if enrichment.Headquarter != "" && enrichment.Headquarter != "Unknown" {
		parts = append(parts, fmt.Sprintf("**Headquarter:** %s", enrichment.Headquarter))
	}
	if enrichment.Vertical != "" && enrichment.Vertical != "Unknown" {
		parts = append(parts, fmt.Sprintf("**Vertical:** %s", enrichment.Vertical))
	}
	if enrichment.BusinessModel != "" && enrichment.BusinessModel != "Unknown" {
		parts = append(parts, fmt.Sprintf("**Business Model:** %s", enrichment.BusinessModel))
	}
	if enrichment.AnnualRevenue != "" && enrichment.AnnualRevenue != "Unknown" {
		parts = append(parts, fmt.Sprintf("**Annual Revenue:** %s", enrichment.AnnualRevenue))
	}
	if enrichment.FundingSeries != "" && enrichment.FundingSeries != "Unknown" {
		parts = append(parts, fmt.Sprintf("**Funding Series:** %s", enrichment.FundingSeries))
	}
	if enrichment.ConfidenceLevel != "" {
		parts = append(parts, fmt.Sprintf("**AI Confidence Level:** %s", enrichment.ConfidenceLevel))
	}

	if len(parts) == 0 {
		return rawText // Fallback to original if no fields extracted
	}

	return strings.Join(parts, "\n")
}
