package gtm

import (
	"context"
	"fmt"

	"github.com/tidbcloud/devops/pkg/infra/clients/llm_cli"
)

// Enricher performs company enrichment using LLM
type Enricher struct {
	llmClient *llm_cli.LLMCli
}

// NewEnricher creates a new Enricher
func NewEnricher(llmClient *llm_cli.LLMCli) *Enricher {
	return &Enricher{
		llmClient: llmClient,
	}
}

// EnrichByEmailDomain performs company enrichment based on email domain
// Returns the raw LLM response text
func (e *Enricher) EnrichByEmailDomain(ctx context.Context, emailDomain string) (string, error) {
	if e.llmClient == nil {
		return "", fmt.Errorf("LLM client not configured")
	}

	prompt := fmt.Sprintf("I just received an email from %s .", emailDomain) + `Search the web to find the company using this exact email domain:

IMPORTANT VERIFICATION STEPS:
1. Search for companies associated with the domain "` + emailDomain + `"
2. For each potential match, visit the company's official website
3. Check the webpage content (contact page, about page, footer, etc.) for email addresses or domain references
4. ONLY return information if the webpage content explicitly confirms they use the email domain "` + emailDomain + `"
5. If you find multiple companies with similar domain names, use webpage content to identify the correct one
6. If the webpage shows a DIFFERENT email domain, discard that result and continue searching
7. If no company webpage confirms using "` + emailDomain + `", return "Unknown" for all fields

Respond ONLY with a JSON object (no markdown code blocks, no additional text):
{
  "company_name": "company name or Unknown",
  "headquarter": "location or Unknown",
  "headquarter_country_code": "ISO 3166-1 alpha-2 country code or empty string",
  "vertical": "industry vertical or Unknown",
  "business_model": "B2B/B2C/B2B2C or Unknown",
  "approximate_annual_revenue": "revenue range or Unknown",
  "funding_series": "funding stage or Unknown",
  "ai_confidence_level": "high/medium/low"
}

Confidence level guidelines:
- "high": Verified company webpage explicitly shows this email domain
- "medium": Strong indirect evidence (company size, industry matches domain pattern)
- "low": Limited or uncertain information

If information cannot be verified from webpage content, use "Unknown" for that field.
If the headquarters country cannot be verified, use an empty string for "headquarter_country_code".
Response must be valid JSON only, no additional explanation.`

	result, err := e.llmClient.SimpleSearch(prompt)
	if err != nil {
		return "", fmt.Errorf("LLM search failed: %w", err)
	}

	return result, nil
}
