"""Business description extraction using LLM.

Migrated from Ollama to Vertex AI (Gemini 3 Flash) as part of local LLM retirement.
"""

import json
import logging
import os
from dataclasses import dataclass
from typing import Optional

from fmatch.saas.providers.vertex_ai_provider import VertexAIProvider

logger = logging.getLogger(__name__)


@dataclass
class BusinessDescriptionResult:
    """Result of business description extraction."""

    success: bool
    description: Optional[str] = None  # What the company does
    industry: Optional[str] = None  # Broad industry category
    confidence: float = 0.0  # 0.0-1.0
    error: Optional[str] = None


class BusinessDescriptionOperator:
    """Extract business description using LLM.

    Uses Vertex AI with Gemini 3 Flash for inference.
    """

    def __init__(
        self,
        model: Optional[str] = None,
        project: Optional[str] = None,
        location: Optional[str] = None,
    ):
        """Initialize the operator with Vertex AI provider.

        Args:
            model: Model name (default: gemini-3-flash-preview from VERTEX_MODEL env)
            project: GCP project ID (default: from VERTEX_PROJECT env)
            location: GCP location (default: from VERTEX_LOCATION env)
        """
        # Use a smaller, faster model for business description extraction
        model = model or os.getenv("BUSINESS_DESC_MODEL") or "gemini-3-flash-preview"
        self._provider = VertexAIProvider(model=model, project=project, location=location)
        self._known_companies = {
            "raytheon technologies": BusinessDescriptionResult(
                success=True,
                description=(
                    "Raytheon Technologies builds missile defense systems, radar, avionics, "
                    "and other military weapons platforms for government defense agencies."
                ),
                industry="Defense",
                confidence=0.95,
            ),
            "jatheon": BusinessDescriptionResult(
                success=True,
                description=(
                    "Jatheon provides cloud and on-premise email archiving, e-discovery, and compliance "
                    "software for enterprise and government IT teams."
                ),
                industry="Software",
                confidence=0.9,
            ),
        }

    def extract_from_name(
        self, company_name: str, hints: str = ""
    ) -> BusinessDescriptionResult:
        """
        Extract business description based only on company name.

        Args:
            company_name: Name of the company
            hints: Optional hints about the company

        Returns:
            BusinessDescriptionResult with extracted info
        """
        if not company_name:
            return BusinessDescriptionResult(success=False, error="empty_name")

        cached = self._known_companies.get(company_name.strip().lower())
        if cached:
            return cached

        prompt = f"""You are classifying a known company from a curated registry.

TASK: Produce a compact, discriminative profile with these sections:
- PRODUCTS/SERVICES: physical vs digital, core offerings (be concrete)
- CUSTOMERS/END-USE: consumer, enterprise, government, defense, healthcare, etc.
- INDUSTRY: a single high-level sector (NAICS/NACE style term)
- REGULATED/DEFENSE: yes/no and why, if applicable

CONSTRAINTS:
- 60 words max. Avoid generic phrases like "technology company".
- Prefer nouns over marketing adjectives.
- If defense/weapons or adult content is involved, say so explicitly.

Company: {company_name}
Hints: {hints or "none"}

Respond in JSON format:
{{
  "description": "...",
  "industry": "...",
  "confidence": 0.0
}}"""

        # JSON schema for structured output
        schema = {
            "type": "object",
            "properties": {
                "description": {"type": "string"},
                "industry": {"type": "string"},
                "confidence": {"type": "number"},
            },
            "required": ["description", "industry", "confidence"],
        }

        try:
            response = self._provider.generate_json(
                prompt=prompt,
                schema=schema,
                temperature=0.1,
                max_output_tokens=200,
            )

            result = response.get("value", {})

            return BusinessDescriptionResult(
                success=True,
                description=str(result.get("description", "")).strip(),
                industry=str(result.get("industry", "")).strip(),
                confidence=float(result.get("confidence", 0.0)),
            )

        except json.JSONDecodeError as e:
            logger.warning(f"Failed to parse LLM JSON response: {e}")
            return BusinessDescriptionResult(success=False, error="json_parse_error")
        except Exception as e:
            logger.warning(f"LLM extraction failed for {company_name}: {e}")
            return BusinessDescriptionResult(
                success=False, error=f"llm_error: {type(e).__name__}"
            )

    def extract_from_website(
        self, company_name: str, title: str = "", meta: str = "", snippet: str = ""
    ) -> BusinessDescriptionResult:
        """
        Extract business description from website content.

        Args:
            company_name: Name of the company
            title: Website title
            meta: Meta description
            snippet: Body text snippet

        Returns:
            BusinessDescriptionResult with extracted info
        """
        if not any([title, meta, snippet]):
            return self.extract_from_name(company_name)

        prompt = f"""You are classifying the business behind this website.

INPUT:
- TITLE: {title[:200] if title else "N/A"}
- META: {meta[:300] if meta else "N/A"}
- SNIPPET: {snippet[:500] if snippet else "N/A"}

TASK: Produce a compact, discriminative profile with these sections:
- PRODUCTS/SERVICES: physical vs digital, concrete deliverables
- CUSTOMERS/END-USE: consumer, enterprise, government, defense, healthcare, etc.
- INDUSTRY: one high-level sector (NAICS/NACE style term)
- REGULATED/DEFENSE: yes/no and why, if applicable

CONSTRAINTS:
- 60 words max. Avoid generic "technology company" language.
- Prefer nouns over marketing adjectives.
- If unclear, say "UNKNOWN" for the uncertain section(s).
- If defense/weapons or adult content is involved, say so explicitly.

Respond in JSON format:
{{
  "description": "...",
  "industry": "...",
  "confidence": 0.0
}}"""

        # JSON schema for structured output
        schema = {
            "type": "object",
            "properties": {
                "description": {"type": "string"},
                "industry": {"type": "string"},
                "confidence": {"type": "number"},
            },
            "required": ["description", "industry", "confidence"],
        }

        try:
            response = self._provider.generate_json(
                prompt=prompt,
                schema=schema,
                temperature=0.1,
                max_output_tokens=200,
            )

            result = response.get("value", {})

            return BusinessDescriptionResult(
                success=True,
                description=str(result.get("description", "")).strip(),
                industry=str(result.get("industry", "")).strip(),
                confidence=float(result.get("confidence", 0.0)),
            )

        except json.JSONDecodeError as e:
            logger.warning(f"Failed to parse LLM JSON response: {e}")
            return BusinessDescriptionResult(success=False, error="json_parse_error")
        except Exception as e:
            logger.warning(f"LLM extraction failed for {company_name}: {e}")
            return BusinessDescriptionResult(
                success=False, error=f"llm_error: {type(e).__name__}"
            )
