"""Three authored citation fixtures; public Crossref metadata only, no AI calls."""
import json
import platform
import time
from datetime import datetime, timezone
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, urlopen


def normalize(title):
    # Deliberately conservative: punctuation and subtitles still matter.
    return " ".join(title.split()).casefold()


def lookup(doi):
    endpoint = "https://api.crossref.org/works/" + quote(doi, safe="")
    request = Request(endpoint, headers={
        "User-Agent": "AIAnonymousCitationExercise/1.0 (https://jabsystems.io/ai-anonymous/)",
        "Accept": "application/json",
    })
    try:
        with urlopen(request, timeout=25) as response:
            message = json.load(response)["message"]
        return {"lookup": "record_returned", "endpoint": endpoint,
                "record_doi": message.get("DOI"),
                "titles": message.get("title", []),
                "authors": [a.get("family", "") for a in message.get("author", [])],
                "published": message.get("published", {}).get("date-parts", []),
                "publisher_url": message.get("URL")}
    except HTTPError as error:
        if error.code == 404:
            return {"lookup": "not_in_crossref", "endpoint": endpoint, "http": 404}
        # Rate limits and service errors remain unresolved; no immediate retry loop.
        return {"lookup": "unresolved", "endpoint": endpoint, "http": error.code}
    except (URLError, TimeoutError, ValueError, KeyError) as error:
        return {"lookup": "unresolved", "endpoint": endpoint, "error": type(error).__name__}


def compare(row, record):
    agrees = record["lookup"] == "record_returned" and any(
        normalize(row["claimed_title"]) == normalize(t) for t in record.get("titles", []))
    return {**row, **record, "title_check": (
        "title_agrees" if agrees else
        "title_differs" if record["lookup"] == "record_returned" else "not_checked"),
        "claim_support": "not_checked"}


def main():
    rows = json.loads(Path(__file__).with_name("citation-fixtures.json").read_text(encoding="utf-8"))
    cache = {}
    results = []
    for row in rows:
        doi = row["doi"]
        if doi not in cache:
            if cache:
                time.sleep(1)
            cache[doi] = lookup(doi)
        results.append(compare(row, cache[doi]))
        if cache[doi]["lookup"] == "unresolved":
            break  # Stop on network/API failure; do not turn it into a citation verdict.
    print(json.dumps({"checked_at": datetime.now(timezone.utc).isoformat(),
                      "python": platform.python_version(), "unique_requests": len(cache),
                      "results": results}, indent=2))
    # Exit 0 means the report was produced, not that any citation is approved.


if __name__ == "__main__":
    main()
