"""Enrich company with subsidiary list from Wikidata relationships."""

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

__transform_id__ = "enrich_subsidiaries"
__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_profile(domain: Optional[str]) -> Optional[Dict[str, Any]]:
    """Get Wikidata profile for domain."""
    try:
        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)
        return profile

    except Exception:
        return None


def _lookup_subsidiaries(wikidata_id: str) -> List[Dict[str, str]]:
    """Query Wikidata relationships table for subsidiaries."""
    try:
        try:
            import duckdb  # type: ignore
        except ImportError:
            return []

        db_path = os.getenv("WIKIDATA_INDEX_PATH", "config/foundrygraph.duckdb")
        if not os.path.exists(db_path):
            return []

        conn = duckdb.connect(db_path, read_only=True)
        try:
            rows = conn.execute(
                """
                SELECT r.child_label, p.domain
                FROM company_relationships r
                LEFT JOIN company_profiles p ON r.child_id = p.wikidata_id
                WHERE r.parent_id = ? AND r.relation_type = 'parent'
                ORDER BY r.child_label
                """,
                [wikidata_id],
            ).fetchall()
        finally:
            conn.close()

        subsidiaries = []
        for child_label, child_domain in rows:
            subsidiaries.append(
                {
                    "name": child_label,
                    "domain": (child_domain or "").lower() if child_domain else None,
                }
            )

        return subsidiaries

    except Exception:
        return []


def enrich_subsidiaries(
    company: Optional[str] = None,
    website: Optional[str] = None,
    domain: Optional[str] = None,
) -> Dict[str, Any]:
    """
    Enrich company with list of subsidiaries from Wikidata.

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

    Returns:
        Dict with subsidiary count and list.

    Examples:
        >>> enrich_subsidiaries(domain="microsoft.com")
        {"subsidiary_count": 58, "subsidiaries": "Activision Blizzard, LinkedIn, GitHub, ...", "confidence": 1.0}
    """

    dom = normalize_domain(website or domain or "")

    # 1. Get Wikidata profile
    profile = _lookup_wikidata_profile(dom)
    if not profile:
        return {
            "subsidiary_count": 0,
            "subsidiaries": "Not Available",
            "confidence": 0.0,
            "source": None,
        }

    # 2. Lookup subsidiaries for this company
    wikidata_id = profile.get("wikidata_id")
    if not wikidata_id:
        return {
            "subsidiary_count": 0,
            "subsidiaries": "Not Available",
            "confidence": 0.0,
            "source": None,
        }

    subsidiaries = _lookup_subsidiaries(wikidata_id)
    if subsidiaries:
        # Limit to first 10 for display purposes
        subsidiary_names = [s["name"] for s in subsidiaries[:10]]
        display_list = ", ".join(subsidiary_names)
        if len(subsidiaries) > 10:
            display_list += f", ... ({len(subsidiaries) - 10} more)"

        return {
            "subsidiary_count": len(subsidiaries),
            "subsidiaries": display_list,
            "confidence": 1.0,
            "source": "wikidata",
        }

    # 3. No subsidiaries found
    return {
        "subsidiary_count": 0,
        "subsidiaries": "Not Available",
        "confidence": 0.0,
        "source": None,
    }
