"""Enrich company revenue from FoundryGraph/Wikidata profiles."""

import json
import logging
from functools import lru_cache
from typing import Any, Dict, Optional

__transform_id__ = "enrich_company_revenue"
__version__ = "1.0.0"
__updated__ = "2025-12-30"

log = logging.getLogger(__name__)

_foundrygraph_connection_getter = None


def _get_foundrygraph_connection():
    """Lazy loader for FoundryGraph connection to avoid startup hang."""
    global _foundrygraph_connection_getter
    if _foundrygraph_connection_getter is None:
        from ..services.foundrygraph_serving import get_foundrygraph_connection
        _foundrygraph_connection_getter = get_foundrygraph_connection
    return _foundrygraph_connection_getter()


@lru_cache(maxsize=1000)
def normalize_domain(url_or_domain: str) -> str:
    """Extract and normalize domain from URL or domain string."""
    if not url_or_domain:
        return ""

    s = url_or_domain.strip().lower()
    if "://" not in s:
        s = "http://" + s

    try:
        from urllib.parse import urlparse

        parsed = urlparse(s)
        domain = parsed.hostname or parsed.path.split("/")[0]
        if domain and domain.startswith("www."):
            domain = domain[4:]
        return domain or ""
    except Exception:
        return ""


def _coerce_number(value: Any) -> Optional[float]:
    if value is None:
        return None
    if isinstance(value, (int, float)):
        return float(value)
    if isinstance(value, str):
        cleaned = value.replace(",", "").replace("$", "").strip()
        if not cleaned:
            return None
        try:
            return float(cleaned)
        except ValueError:
            return None
    return None


def _parse_revenue_payload(payload: Any) -> Optional[Dict[str, Any]]:
    if not payload:
        return None
    if isinstance(payload, str):
        try:
            payload = json.loads(payload)
        except (json.JSONDecodeError, TypeError):
            return None
    if not isinstance(payload, dict):
        return None
    return payload


def enrich_company_revenue(
    company: Optional[str] = None,
    website: Optional[str] = None,
    domain: Optional[str] = None,
) -> Dict[str, Any]:
    """
    Enrich company with revenue from Wikidata/FoundryGraph profiles.

    Args:
        company: Company name (not used currently, reserved for future)
        website: Company website URL
        domain: Domain (if already extracted)

    Returns:
        Dict with revenue information.
    """
    dom = normalize_domain(website or domain or "")
    if not dom:
        return {
            "revenue": "",
            "currency": "",
            "year": "",
            "confidence": 0.0,
            "source": None,
        }

    try:
        conn = _get_foundrygraph_connection()
    except Exception as exc:
        log.debug("FoundryGraph connection unavailable: %s", exc)
        conn = None

    if conn is not None:
        try:
            row = conn.execute(
                """
                SELECT revenue_amount, revenue_currency, revenue_year
                FROM wikidata_profiles
                WHERE domain = ?
                LIMIT 1
                """,
                [dom],
            ).fetchone()
            if row and any(row):
                amount = _coerce_number(row[0])
                currency = str(row[1] or "").strip()
                year = str(row[2] or "").strip()
                return {
                    "revenue": amount if amount is not None else "",
                    "currency": currency,
                    "year": year,
                    "confidence": 1.0 if amount is not None else 0.0,
                    "source": "foundrygraph",
                }
        except Exception as exc:
            log.debug("FoundryGraph wikidata_profiles lookup failed: %s", exc)

        try:
            row = conn.execute(
                """
                SELECT revenue
                FROM company_profiles
                WHERE domain = ?
                LIMIT 1
                """,
                [dom],
            ).fetchone()
            payload = _parse_revenue_payload(row[0] if row else None)
            if payload:
                amount = _coerce_number(payload.get("amount"))
                currency = str(payload.get("currency") or payload.get("currency_code") or "").strip()
                year = str(payload.get("year") or payload.get("as_of") or "").strip()
                return {
                    "revenue": amount if amount is not None else "",
                    "currency": currency,
                    "year": year,
                    "confidence": 1.0 if amount is not None else 0.0,
                    "source": "foundrygraph",
                }
        except Exception as exc:
            log.debug("FoundryGraph company_profiles lookup failed: %s", exc)

    return {
        "revenue": "",
        "currency": "",
        "year": "",
        "confidence": 0.0,
        "source": None,
    }
