"""Public endpoints for Wikidata company lookups."""

import os
from pathlib import Path
from typing import Dict, Any, Optional
from fastapi import APIRouter, Query, HTTPException

router = APIRouter(prefix="/api/v2", tags=["wikidata"])


def _get_wikidata_db_path() -> Path:
    """Get path to wikidata DuckDB file from environment or default location."""
    db_path_str = os.getenv("WIKIDATA_DB_PATH", "config/foundrygraph.duckdb")
    db_path = Path(db_path_str)

    # If absolute, use as-is
    if db_path.is_absolute():
        if not db_path.exists():
            raise HTTPException(
                status_code=503,
                detail=f"Wikidata database not found at {db_path}"
            )
        return db_path

    # Try relative to /app first (container standard)
    app_path = Path("/app") / db_path
    if app_path.exists():
        return app_path

    # Fall back to current directory
    cwd_path = Path.cwd() / db_path
    if cwd_path.exists():
        return cwd_path

    raise HTTPException(
        status_code=503,
        detail=f"Wikidata database not found. Tried: {db_path}, {app_path}, {cwd_path}"
    )


def _fetch_rows(conn, like_pattern: str, limit: int):
    """
    Attempt lookup using dump schema first (country/industry columns), then legacy
    schema (countries/industries JSON) for backward compatibility.
    """
    queries = [
        """
        SELECT
            wikidata_id,
            label,
            COALESCE(country, '') AS country,
            COALESCE(industry, '') AS industry,
            website
        FROM company_profiles
        WHERE lower(label) LIKE ?
        ORDER BY label
        LIMIT ?
        """,
        """
        SELECT
            wikidata_id,
            label,
            COALESCE(json_extract_string(countries, '$[0].label'), '') AS country,
            COALESCE(json_extract_string(industries, '$[0].label'), '') AS industry,
            website
        FROM company_profiles
        WHERE lower(label) LIKE ?
        ORDER BY label
        LIMIT ?
        """,
    ]

    last_error: Optional[str] = None
    for sql in queries:
        try:
            return conn.execute(sql, [like_pattern, limit]).fetchall()
        except Exception as exc:
            last_error = str(exc)
    raise HTTPException(
        status_code=500,
        detail=f"Database query failed: {last_error or 'unknown error'}",
    )


@router.get("/wikidata/lookup")
async def lookup_wikidata_company(
    name: str = Query(..., min_length=2, description="Company name to search"),
    limit: int = Query(10, ge=1, le=50, description="Maximum results to return")
) -> Dict[str, Any]:
    """
    Public endpoint for Wikidata company lookups.
    Searches by company name and returns basic company information.
    """
    import duckdb

    db_path = _get_wikidata_db_path()

    try:
        with duckdb.connect(str(db_path), read_only=True) as conn:
            try:
                conn.execute("LOAD json")
            except Exception:
                pass

            like_pattern = f"%{name.lower()}%"
            rows = _fetch_rows(conn, like_pattern, limit)

            if not rows:
                return {
                    "query": name,
                    "results": [],
                    "count": 0
                }

            first = rows[0]
            qid, label, country, industry, website = first

            all_results = []
            for qid, label, country, industry, website in rows:
                all_results.append({
                    "qid": qid,
                    "name": label,
                    "country": country or None,
                    "industry": industry or None,
                    "website": website or None
                })

            return {
                "qid": qid,
                "name": label,
                "country": country or None,
                "industry": industry or None,
                "website": website or None,
                "all_results": all_results if len(all_results) > 1 else None
            }

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Database query failed: {str(e)}"
        )
