#!/usr/bin/env python3
"""JERZPUB Scrape — public DOI metadata refresher, version 1.0.0.

Python 3.9+; standard library only. Queries Crossref's public API by DOI.
Does not scrape paywalls, download papers, or verify scientific findings.
Run --help for usage; --dry-run and --self-test do not use the network.
"""
import argparse
import csv
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
import hashlib
import io
import json
from pathlib import Path
import re
import sys
import time
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlencode
from urllib.request import Request, urlopen

VERSION = "1.0.0"
MAX_BYTES = 5 * 1024 * 1024


def now():
    return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")


def normalize_doi(value):
    value = str(value or "").strip()
    value = re.sub(r"^https?://(?:dx\.)?doi\.org/", "", value, flags=re.I)
    if not re.fullmatch(r"10\.\d{4,9}/[^\s<>\x00-\x1f]+", value, flags=re.I):
        raise ValueError("Invalid DOI: " + repr(value[:160]))
    return value.lower()


def candidates(path):
    if path.suffix.lower() == ".csv":
        with path.open(encoding="utf-8-sig", newline="") as handle:
            reader = csv.DictReader(handle)
            if not reader.fieldnames or "doi" not in reader.fieldnames:
                raise ValueError("CSV input needs a doi column")
            return list(reader)
    value = json.loads(path.read_text(encoding="utf-8-sig"))
    rows = value.get("records") if isinstance(value, dict) else value
    if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows):
        raise ValueError("JSON input must be an array of objects or an object with a records array")
    return rows


def collect(rows, direct):
    identifiers, skipped, invalid = [], [], []
    for number, row in enumerate(rows, 1):
        candidate = row.get("doi")
        if not candidate:
            skipped.append({"row": number, "id": row.get("id"), "reason": "No DOI recorded; no DOI inferred from a title or PubMed identifier"})
            continue
        try:
            value = normalize_doi(candidate)
            if value not in identifiers:
                identifiers.append(value)
        except ValueError as error:
            invalid.append({"row": number, "id": row.get("id"), "value": str(candidate), "error": str(error)})
    for candidate in direct:
        value = normalize_doi(candidate)
        if value not in identifiers:
            identifiers.append(value)
    return identifiers, skipped, invalid


def retry_seconds(value, fallback):
    if value:
        try:
            return max(fallback, min(60.0, float(value)))
        except ValueError:
            try:
                return max(fallback, min(60.0, (parsedate_to_datetime(value) - datetime.now(timezone.utc)).total_seconds()))
            except (TypeError, ValueError, OverflowError):
                pass
    return fallback


def flatten(message):
    title = message.get("title")
    container = message.get("container-title")
    authors = []
    for author in message.get("author") or []:
        if not isinstance(author, dict):
            continue
        name = " ".join(str(author.get(key) or "").strip() for key in ("given", "family")).strip()
        if not name:
            name = str(author.get("name") or "").strip()
        if name:
            authors.append(name)
    issued = message.get("issued") or {}
    return {
        "doi": normalize_doi(message.get("DOI")),
        "title": title[0] if isinstance(title, list) and title else None,
        "authors": authors,
        "containerTitle": container[0] if isinstance(container, list) and container else None,
        "publisher": message.get("publisher"), "type": message.get("type"),
        "issuedDateParts": issued.get("date-parts") if isinstance(issued, dict) else None,
        "url": message.get("URL"),
        "license": message.get("license") or [],
    }


def fetch(identifier, mailto, timeout, delay, retries):
    endpoint = "https://api.crossref.org/works/" + quote(identifier, safe="")
    if mailto:
        endpoint += "?" + urlencode({"mailto": mailto})
    agent = "JERZPUB-Scrape/" + VERSION + " (+https://jerseypublishers.com"
    agent += ("; mailto:" + mailto if mailto else "") + ")"
    result = {"requestedDoi": identifier, "requestedAt": now(), "endpoint": endpoint,
              "provider": "Crossref REST API", "status": "error", "attempts": 0}
    for attempt in range(retries + 1):
        result["attempts"] = attempt + 1
        try:
            request = Request(endpoint, headers={"User-Agent": agent, "Accept": "application/json"})
            with urlopen(request, timeout=timeout) as response:
                status = response.status
                raw = response.read(MAX_BYTES + 1)
                if len(raw) > MAX_BYTES:
                    raise ValueError("Response exceeds the 5 MiB safety limit")
                payload = json.loads(raw.decode("utf-8"))
                if not isinstance(payload, dict) or payload.get("status") != "ok" or not isinstance(payload.get("message"), dict):
                    raise ValueError("Unexpected Crossref response shape")
                message = payload["message"]
                if normalize_doi(message.get("DOI")) != identifier:
                    raise ValueError("Returned DOI does not match the requested DOI")
                result.update({"status": "ok", "retrievedAt": now(), "httpStatus": status,
                               "metadata": flatten(message), "responseSha256": hashlib.sha256(raw).hexdigest()})
                return result, raw
        except HTTPError as error:
            result.update({"httpStatus": error.code, "errorType": "http", "error": str(error)})
            if error.code in (429, 500, 502, 503, 504) and attempt < retries:
                suggested = retry_seconds(error.headers.get("Retry-After") if error.headers else None, max(delay, 2 ** attempt))
                # Never retry earlier than a provider's longer Retry-After request.
                if suggested >= 60:
                    result["error"] += "; retry deferred: choose a later run"
                    break
                time.sleep(suggested)
                continue
            break
        except (URLError, TimeoutError, OSError) as error:
            result.update({"errorType": "network", "error": str(error)})
            if attempt < retries:
                time.sleep(max(delay, 2 ** attempt))
                continue
            break
        except (ValueError, UnicodeError, TypeError) as error:
            result.update({"errorType": "validation", "error": str(error)})
            break
    result["finishedAt"] = now()
    return result, None


def csv_value(value):
    if value is None:
        return ""
    if isinstance(value, (dict, list)):
        value = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
    value = str(value)
    # Keep untrusted remote metadata from becoming a spreadsheet formula.
    return "'" + value if value.startswith(("=", "+", "-", "@", "\t", "\r")) else value


def self_test():
    assert normalize_doi(" https://doi.org/10.1000/ABC ") == "10.1000/abc"
    for bad in ("https://example.com/10.1000/a", "10.1000/a b", "", "10.abc/a"):
        try:
            normalize_doi(bad)
        except ValueError:
            pass
        else:
            raise AssertionError("Accepted invalid DOI")
    identifiers, skipped, invalid = collect([{"doi": "10.1000/a"}, {"doi": "10.1000/A"}, {}, {"doi": "bad"}], [])
    assert identifiers == ["10.1000/a"] and len(skipped) == len(invalid) == 1
    record = flatten({"DOI": "10.1000/a", "title": ["A title"], "author": [{"given": "A", "family": "Researcher"}], "issued": {"date-parts": [[2020]]}})
    assert record["authors"] == ["A Researcher"] and record["issuedDateParts"] == [[2020]]
    assert record["publisher"] is None and csv_value("=SUM(1,2)").startswith("'=")
    print("Offline self-test passed: DOI validation, de-duplication, missing identifiers, metadata flattening, CSV formula protection.")


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="Examples:\n  python3 jerzpub-scrape.py --dry-run\n  python3 jerzpub-scrape.py --input sources.csv --mailto you@example.com --output-dir refreshed-2026-10-17\n  python3 jerzpub-scrape.py --doi 10.3390/agronomy11112293 --dry-run\n  python3 jerzpub-scrape.py --self-test\n\nCrossref API documentation: https://www.crossref.org/documentation/retrieve-metadata/rest-api/\nA successful lookup confirms registry metadata retrieval, not source validity or scientific claims.")
    parser.add_argument("--input", type=Path, help="JSON index or CSV containing doi values; defaults to sources.json next to this script")
    parser.add_argument("--doi", action="append", default=[], help="DOI to retrieve; may be repeated")
    parser.add_argument("--output-dir", type=Path, default=Path("refreshed"), help="New output directory (default: refreshed)")
    parser.add_argument("--mailto", help="Your contact email for Crossref's polite pool; optional, never invented")
    parser.add_argument("--timeout", type=float, default=20, help="Per-request timeout in seconds, 1–120 (default: 20)")
    parser.add_argument("--delay", type=float, default=1, help="Minimum seconds between lookups, at least 1 (default: 1)")
    parser.add_argument("--retries", type=int, default=1, help="Retries for temporary HTTP/network errors, 0–3 (default: 1)")
    parser.add_argument("--dry-run", action="store_true", help="Print validated lookup plan; no requests or output files")
    parser.add_argument("--self-test", action="store_true", help="Run offline checks and exit")
    args = parser.parse_args()
    if args.self_test:
        self_test()
        return 0
    if not 1 <= args.timeout <= 120 or not 1 <= args.delay <= 60 or not 0 <= args.retries <= 3:
        parser.error("timeout must be 1–120; delay 1–60; retries 0–3")
    if args.mailto and not re.fullmatch(r"[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+", args.mailto):
        parser.error("mailto must be a contact email address")
    input_path = args.input
    if input_path is None and not args.doi:
        input_path = Path(__file__).resolve().with_name("sources.json")
        if not input_path.is_file():
            parser.error("No sources.json beside this script. Download sources.json into the same folder, pass --input PATH, or supply one or more --doi values. Use --help for examples.")
    try:
        rows = candidates(input_path) if input_path else []
        identifiers, skipped, invalid = collect(rows, args.doi)
    except (ValueError, OSError, csv.Error) as error:
        parser.error(str(error))
    if not identifiers:
        parser.error("No valid DOI identifiers found")
    input_sha256 = hashlib.sha256(input_path.read_bytes()).hexdigest() if input_path else None
    if args.dry_run:
        print(json.dumps({"mode": "dry-run", "networkRequests": 0, "doiCount": len(identifiers),
                          "dois": identifiers, "skipped": skipped, "invalid": invalid,
                          "inputSha256": input_sha256}, ensure_ascii=False, indent=2))
        return 2 if invalid else 0
    output = args.output_dir
    if output.exists() and any(output.iterdir()):
        parser.error("Output directory is not empty; choose a new directory to preserve previous results")
    output.mkdir(parents=True, exist_ok=True)
    (output / "responses").mkdir()
    run = {"tool": "JERZPUB Scrape", "version": VERSION, "startedAt": now(),
           "inputFile": str(input_path) if input_path else None, "inputSha256": input_sha256,
           "provider": "Crossref REST API", "lookupCount": len(identifiers), "timeoutSeconds": args.timeout,
           "delaySeconds": args.delay, "maxRetries": args.retries, "skipped": skipped, "invalid": invalid,
           "scope": "Public DOI registry metadata only; no paper full text or scientific verification"}
    results = []
    failures = []
    try:
        for number, identifier in enumerate(identifiers, 1):
            if number > 1:
                time.sleep(args.delay)
            result, raw = fetch(identifier, args.mailto, args.timeout, args.delay, args.retries)
            if raw is not None:
                filename = hashlib.sha256(identifier.encode()).hexdigest()[:24] + ".json"
                (output / "responses" / filename).write_bytes(raw)
                result["responseFile"] = "responses/" + filename
            else:
                failures.append(result)
            results.append(result)
            # A JSONL checkpoint is useful if an operator interrupts a long run.
            with (output / "results.jsonl").open("a", encoding="utf-8") as handle:
                handle.write(json.dumps(result, ensure_ascii=False) + "\n")
            print(f"{number}/{len(identifiers)} {identifier}: {result['status']}", file=sys.stderr)
    except KeyboardInterrupt:
        run["interrupted"] = True
        print("Interrupted; completed results and run provenance will be saved.", file=sys.stderr)
    run.update({"finishedAt": now(), "completed": len(results), "succeeded": len(results) - len(failures), "failed": len(failures)})
    for name, value in (("run.json", run), ("crossref-results.json", {"run": run, "results": results}), ("errors.json", failures)):
        (output / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    fields = ["doi", "status", "title", "authors", "containerTitle", "publisher", "type", "issuedDateParts", "url", "retrievedAt", "error"]
    with (output / "crossref-results.csv").open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        for result in results:
            row = {"doi": result["requestedDoi"], "status": result["status"], "retrievedAt": result.get("retrievedAt"), "error": result.get("error")}
            row.update(result.get("metadata") or {})
            writer.writerow({field: csv_value(row.get(field)) for field in fields})
    print(f"Saved {len(results)} results ({len(failures)} failures) to {output}")
    return 2 if failures or invalid or run.get("interrupted") else 0


if __name__ == "__main__":
    raise SystemExit(main())
