import os
from typing import Dict, Any

import pytest
import requests


BASE_URL = os.getenv(
    "WIKIDATA_API_URL",
    "https://fuzzy-matcher-api-851177029256.us-central1.run.app",
)
RUN_LIVE = os.getenv("RUN_WIKIDATA_LIVE") == "1"

pytestmark = pytest.mark.skipif(
    not RUN_LIVE,
    reason="Set RUN_WIKIDATA_LIVE=1 to exercise the live Wikidata lookup API",
)


def _lookup(name: str, limit: int = 5) -> Dict[str, Any]:
    resp = requests.get(
        f"{BASE_URL}/api/v2/wikidata/lookup",
        params={"name": name, "limit": limit},
        timeout=30,
    )
    resp.raise_for_status()
    return resp.json()


def test_lookup_microsoft():
    data = _lookup("Microsoft", limit=5)
    assert data.get("qid") == "Q2283"
    website = (data.get("website") or "").lower()
    assert "microsoft.com" in website


def test_lookup_google():
    data = _lookup("Google", limit=5)
    assert data.get("qid") == "Q95"
    website = (data.get("website") or "").lower()
    assert "google.com" in website


def test_lookup_no_results_returns_empty():
    missing_name = "this-company-name-should-not-exist-xyz123"
    data = _lookup(missing_name, limit=3)
    assert data.get("count", 0) == 0
    assert data.get("results") == []


def test_lookup_handles_special_characters():
    data = _lookup("AT&T", limit=5)
    # Allow either top-level qid or results collection depending on match count.
    assert ("qid" in data and data["qid"]) or data.get("results")
