"""Enrich company headquarters location from Wikidata profiles."""

from typing import Dict, Any, Optional, List
from functools import lru_cache

__transform_id__ = "enrich_company_headquarters"
__version__ = "1.0.0"
__updated__ = "2025-10-07"


@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]
        # Remove www prefix
        if domain and domain.startswith("www."):
            domain = domain[4:]
        return domain or ""
    except:
        return ""


def _lookup_wikidata_headquarters(
    domain: Optional[str],
) -> Optional[List[Dict[str, str]]]:
    """Query Wikidata profiles for headquarters data."""
    try:
        import os

        if os.getenv("FM_COMPANY_TO_DOMAIN_WIKIDATA", "true").lower() != "true":
            return None

        from . import wikidata_profiles

        normalized_domain = (domain or "").lower()
        if not normalized_domain:
            return None

        profile = wikidata_profiles.get_profile_for_domain(normalized_domain)
        if not profile:
            return None

        headquarters = profile.get("headquarters", [])
        if headquarters:
            return headquarters

        return None

    except Exception:
        return None


def enrich_company_headquarters(
    company: Optional[str] = None,
    website: Optional[str] = None,
    domain: Optional[str] = None,
) -> Dict[str, Any]:
    """
    Enrich company with headquarters location from Wikidata.

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

    Returns:
        Dict with headquarters information.

    Examples:
        >>> enrich_company_headquarters(domain="simbasleep.ca")
        {"headquarters": "London", "confidence": 1.0}
    """

    dom = normalize_domain(website or domain or "")

    # 1. Check Wikidata profiles (40K+ companies)
    wikidata_hq = _lookup_wikidata_headquarters(dom)
    if wikidata_hq:
        # Return primary HQ (first) and all HQ locations
        hq_labels = [hq.get("label", "") for hq in wikidata_hq if hq.get("label")]
        if hq_labels:
            return {
                "headquarters": hq_labels[0],
                "all_headquarters": ", ".join(hq_labels),
                "confidence": 1.0,
                "source": "wikidata",
            }

    # 2. No headquarters data found
    return {
        "headquarters": "Not Available",
        "all_headquarters": "",
        "confidence": 0.0,
        "source": None,
    }
