#!/usr/bin/env python3
"""Verify the archived @goodjavascript/dotenv@1.0.0 entry point.

Python standard library only. Downloads JSON metadata, package.json and the
known 840-byte index.js into memory. Never installs, imports, executes or saves
package code, and never contacts the network destinations inside that code.
Prints a dated JSON evidence projection; a mismatch fails with nonzero status.
"""

import base64
from datetime import datetime, timezone
import hashlib
import json
import sys
from urllib.parse import quote
from urllib.request import Request, urlopen

SWH = "https://archive.softwareheritage.org/api/1"
PACKAGE = "@goodjavascript/dotenv"
VERSION = "1.0.0"
ORIGIN = f"https://www.npmjs.com/package/{PACKAGE}"
EXPECTED = "a5666532c367714568c5d112300e41d3c3fd6b8665c94f2bb98f5d74fc4d2d6c"
MANIFEST = "https://data.jsdelivr.com/v1/package/npm/%40goodjavascript%2Fdotenv@1.0.0/flat"


def now():
    return datetime.now(timezone.utc).isoformat()


def require(condition, message):
    if not condition:
        raise ValueError(message)


def verify():
    observations = []

    def fetch(url, limit=2_000_000):
        request = Request(url, headers={"User-Agent": "CGSEC-dotenv-recovery-verifier/2.0"})
        with urlopen(request, timeout=30) as response:
            data = response.read(limit + 1)
            require(len(data) <= limit, "Response exceeded expected size limit")
            observations.append({"url": url, "observed_at": now(), "status": response.status,
                                 "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest(),
                                 "pagination_link": response.headers.get("Link")})
            return data

    def get_json(url):
        return json.loads(fetch(url))

    started = now()
    origin_api = f"{SWH}/origin/{quote(ORIGIN, safe='')}/"
    origin = get_json(origin_api + "get/")
    require(origin["url"] == ORIGIN and "npm" in origin["visit_types"], "Unexpected archive origin")
    visits = get_json(origin_api + "visits/?per_page=20")
    visits_link = observations[-1]["pagination_link"]
    snapshots = []
    release_id = None
    for visit in visits:
        require(visit["origin"] == ORIGIN, "Visit belongs to another origin")
        if visit["type"] != "npm" or not visit.get("snapshot"):
            continue
        snapshot = get_json(f"{SWH}/snapshot/{visit['snapshot']}/")
        snapshots.append({"visit": visit["visit"], "visit_date": visit["date"], "snapshot": snapshot})
        branch = snapshot["branches"].get(f"releases/{VERSION}")
        if branch:
            require(branch["target_type"] == "release", "Unexpected snapshot target type")
            release_id = branch["target"]
            break
        require(snapshot.get("next_branch") is None,
                "Snapshot is paginated; this case-specific verifier needs manual review")
    require(release_id is not None,
            "Release not found in first visit page; review pagination" if visits_link
            else "Requested release absent from the observed snapshots")
    release = get_json(f"{SWH}/release/{release_id}/")
    require(release["name"] == VERSION and release["target_type"] == "directory", "Unexpected archive release")
    root = get_json(f"{SWH}/directory/{release['target']}/")
    directory = next(entry for entry in root if entry["name"] == "package" and entry["type"] == "dir")
    entries = get_json(f"{SWH}/directory/{directory['target']}/")
    index = next(entry for entry in entries if entry["name"] == "index.js" and entry["type"] == "file")
    package = next(entry for entry in entries if entry["name"] == "package.json" and entry["type"] == "file")
    package_bytes = fetch(f"{SWH}/content/sha256:{package['checksums']['sha256']}/raw/", limit=100_000)
    require(hashlib.sha256(package_bytes).hexdigest() == package["checksums"]["sha256"], "package.json hash mismatch")
    package_json = json.loads(package_bytes)
    require(package_json["name"] == PACKAGE and package_json["version"] == VERSION, "Package identity mismatch")
    require(package_json.get("main") == "index.js", "Entry point changed")

    manifest = get_json(MANIFEST)
    cdn = next(entry for entry in manifest["files"] if entry["name"] == "/index.js")
    cdn_hash = base64.b64decode(cdn["hash"], validate=True).hex()
    archive_hash = index["checksums"]["sha256"]
    require(cdn_hash == archive_hash == EXPECTED, "Archive/CDN/reference digest mismatch")
    require(index["length"] == cdn["size"] == 840, "Unexpected recorded file size")
    data = fetch(f"{SWH}/content/sha256:{archive_hash}/raw/", limit=840)
    recovered_hash = hashlib.sha256(data).hexdigest()
    require(len(data) == 840 and recovered_hash == EXPECTED, "Recovered file identity mismatch")

    return {
        "started_at": started, "completed_at": now(),
        "verification": {"package": PACKAGE, "version": VERSION, "file": "index.js", "bytes": len(data),
                         "sha256": recovered_hash, "archive_and_cdn_match": True},
        "discovery": {"origin": origin, "visits": visits, "examined_snapshots": snapshots,
                      "selected_release": release_id},
        "archive": {"release": release_id, "root_directory": release["target"], "package_directory": directory["target"],
                    "index_sha256": archive_hash, "package_json_sha256": package["checksums"]["sha256"]},
        "package_metadata": {"name": package_json["name"], "version": package_json["version"],
                             "main": package_json.get("main"), "scripts": package_json.get("scripts")},
        "cdn_file": {"name": cdn["name"], "bytes": cdn["size"], "sha256": cdn_hash},
        "observations": observations,
        "limitations": ["A file-identity check, not a reconstruction of the complete npm tarball.",
                        "No package code executed or saved; behavior requires separate static inspection.",
                        "Archive availability is observed at the request times, not guaranteed."],
    }


if __name__ == "__main__":
    try:
        print(json.dumps(verify(), indent=2))
    except Exception as error:
        print(f"Verification failed: {error}", file=sys.stderr)
        sys.exit(1)
