"""Enrich company stock ticker and exchange from Wikidata external IDs."""

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

__transform_id__ = "enrich_stock_info"
__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_stock_info(wikidata_id: str) -> Dict[str, str]:
    """Query Wikidata external_ids table for stock information."""
    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 id_type, id_value, qualifier_value
                FROM company_external_ids
                WHERE wikidata_id = ?
                AND id_type IN ('ticker', 'stock_exchange', 'isin')
                """,
                [wikidata_id],
            ).fetchall()
        finally:
            conn.close()

        result = {}
        for id_type, id_value, qualifier_value in rows:
            if id_type == "ticker":
                result["ticker"] = id_value
                # Qualifier might contain the exchange
                if qualifier_value:
                    result["exchange"] = qualifier_value
            elif id_type == "stock_exchange" and "exchange" not in result:
                result["exchange"] = id_value
            elif id_type == "isin":
                result["isin"] = id_value

        return result

    except Exception:
        return {}


def enrich_stock_info(
    company: Optional[str] = None,
    website: Optional[str] = None,
    domain: Optional[str] = None,
) -> Dict[str, Any]:
    """
    Enrich company with stock ticker and exchange from Wikidata.

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

    Returns:
        Dict with stock information (ticker, exchange, isin).

    Examples:
        >>> enrich_stock_info(domain="microsoft.com")
        {"ticker": "MSFT", "exchange": "NASDAQ", "isin": "US5949181045", "confidence": 1.0}
    """

    dom = normalize_domain(website or domain or "")

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

    # 2. Lookup stock info for this company
    wikidata_id = profile.get("wikidata_id")
    if not wikidata_id:
        return {
            "ticker": "Not Available",
            "exchange": "Not Available",
            "isin": "Not Available",
            "confidence": 0.0,
            "source": None,
        }

    stock_info = _lookup_stock_info(wikidata_id)
    if stock_info:
        return {
            "ticker": stock_info.get("ticker", "Not Available"),
            "exchange": stock_info.get("exchange", "Not Available"),
            "isin": stock_info.get("isin", "Not Available"),
            "confidence": 1.0,
            "source": "wikidata",
        }

    # 3. No stock info found
    return {
        "ticker": "Not Available",
        "exchange": "Not Available",
        "isin": "Not Available",
        "confidence": 0.0,
        "source": None,
    }
