"""LLM-based domain prediction for company names.

This module provides domain prediction using an injected LLM provider
that implements the ILLMProvider protocol.
"""

from __future__ import annotations

import logging
from typing import Optional, TYPE_CHECKING

if TYPE_CHECKING:
    from ..types import ILLMProvider

logger = logging.getLogger(__name__)


def predict_domain_with_llm(
    company_name: str,
    *,
    llm_provider: Optional["ILLMProvider"] = None,
) -> Optional[str]:
    """Use LLM to predict domain for a company name.

    Args:
        company_name: Company name
        llm_provider: LLM provider implementing ILLMProvider protocol.
                     If None, LLM prediction is skipped.

    Returns:
        Predicted domain or None if LLM unavailable/failed
    """
    if not company_name:
        return None

    # LLM provider must be injected explicitly
    provider = llm_provider
    if provider is None:
        logger.debug("LLM provider not supplied; skipping LLM prediction")
        return None

    try:
        # Define JSON schema for response
        schema = {
            "type": "object",
            "properties": {
                "domain": {"type": "string"},
                "confidence": {"type": "string", "enum": ["high", "medium", "low"]},
            },
            "required": ["domain", "confidence"],
        }

        # Craft prompt with examples
        prompt = f"""Given a company name, predict their most likely primary domain (website).

Examples:
- "Microsoft" -> microsoft.com
- "Salesforce" -> salesforce.com
- "Google" -> google.com
- "Red Hat" -> redhat.com
- "JP Morgan Chase" -> jpmorganchase.com
- "AT&T" -> att.com

Respond with JSON: {{"domain": "example.com", "confidence": "high|medium|low"}}

Company name: "{company_name}"

Only respond with the JSON, nothing else."""

        # Call LLM
        result = provider.generate_json(prompt, schema=schema, num_predict=64)

        if result and isinstance(result, dict):
            value = result.get("value", {})
            if isinstance(value, dict):
                domain = value.get("domain", "").strip().lower()
                confidence = value.get("confidence", "low").lower()

                # Validate domain format
                if domain and "." in domain and " " not in domain:
                    # Remove protocol if present
                    domain = domain.replace("http://", "").replace("https://", "")
                    domain = domain.split("/")[0]  # Remove path

                    # Return with confidence
                    logger.debug(
                        f"LLM predicted {company_name} -> {domain} ({confidence})"
                    )
                    return domain if confidence in ["high", "medium"] else None

    except Exception as e:
        logger.debug(f"LLM domain prediction failed for '{company_name}': {e}")

    return None
