#!/usr/bin/env python3
"""Retrieve selected Crossref fields for one fixed paper/notice pair.

Standard library only. Makes two HTTPS requests and prints JSON.
This is a documented case lookup, not a general retraction detector or a
scientific-quality assessment. Publisher pages must be read separately.
"""

from datetime import datetime, timezone
import json
import platform
from urllib.request import Request, urlopen


ORIGINAL = "10.1038/s41586-023-05742-0"
NOTICE = "10.1038/s41586-023-06774-2"
FIELDS = ("DOI", "title", "type", "published", "published-online",
          "published-print", "update-to", "relation", "URL")


def retrieve(doi):
    url = "https://api.crossref.org/works/" + doi
    request = Request(url, headers={
        "User-Agent": "Gumi-research-note/1.0 (https://gumi.ink/)",
        "Accept": "application/json",
    })
    with urlopen(request, timeout=30) as response:
        status = response.status
        body = json.load(response)
    if status != 200 or body["message"]["DOI"].casefold() != doi.casefold():
        raise RuntimeError("Unexpected response for " + doi)
    selected = {key: body["message"][key] for key in FIELDS if key in body["message"]}
    return {"request_url": url, "http_status": status, "selected_fields": selected}


def summarize(original, notice):
    updates = [entry for entry in notice.get("update-to", [])
               if entry.get("type") == "retraction" and entry.get("DOI", "").casefold() == ORIGINAL.casefold()]
    events = [{"target_doi": entry["DOI"], "type": entry["type"],
               "source": entry.get("source"),
               "date_parts": entry.get("updated", {}).get("date-parts")}
              for entry in updates]
    # A shared target/type/date is only a grouping key for this recorded pair;
    # it is not a universal event-deduplication rule for scholarly records.
    groups = {(entry["target_doi"].casefold(), entry["type"], json.dumps(entry["date_parts"]))
              for entry in events}
    return {
        "original_relation_is_empty": original.get("relation") == {},
        "original_update_types": sorted({entry.get("type", "") for entry in original.get("update-to", [])}),
        "notice_retraction_rows_pointing_to_original": events,
        "row_count": len(events),
        "distinct_target_type_date_groups_in_this_pair": len(groups),
        "interpretation_limit": "Missing metadata is not proof of no retraction; repeated sources are not automatically separate events.",
    }


def main():
    records = {"original": retrieve(ORIGINAL), "notice": retrieve(NOTICE)}
    result = {
        "checked_at_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "environment": {"python": platform.python_version(), "platform": platform.platform()},
        "scope": "Only two fixed Crossref records; no full text, publisher-page scraping, authentication, or scientific replication.",
        "records": records,
        "observations": summarize(records["original"]["selected_fields"], records["notice"]["selected_fields"]),
        "status": "retrieved",
    }
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
