"""Download GitHub malware advisories (npm) for a fixed window into an immutable raw snapshot.

Run from the project folder:
    python code/collect.py                          # study window
    python code/collect.py 2026-09-28..2026-10-25   # any other published range

Output:
    data/raw/<UTC timestamp>/page_001.json, page_002.json, ...
    data/raw/<UTC timestamp>/manifest.json
"""
import json
import sys
import time
from datetime import datetime, timezone
from pathlib import Path

import httpx

BASE = "https://api.github.com/advisories"

# TODO 1: the query string, written as a dict. httpx builds "?type=...&..." from it.
PARAMS = {
    "type": "malware",                      # required: the default excludes malware
    "ecosystem": "npm",                     # design choice: filter server side, fewer requests
    "published": "2026-10-26..2026-11-22",  # four completed UTC weeks, both ends inclusive
    "per_page": 100,                        # the API maximum
}

# Path(__file__) is this script; .parent.parent climbs code/ -> project folder.
# This makes the output location independent of where you run the script from.
OUT = Path(__file__).resolve().parent.parent / "data" / "raw"

MIN_REMAINING = 5   # stop before exhausting the hourly quota
PAUSE_SECONDS = 1   # be polite between pages (helps avoid secondary throttling)


def utc_now():
    """Current time as an ISO 8601 string in UTC, e.g. 2026-11-24T10:15:00+00:00."""
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def fetch_all():
    # One folder per run, named by the UTC time it started.
    # exist_ok=False makes mkdir fail if the folder exists, so a run can never
    # overwrite or mix into an earlier snapshot. (That is the answer to Q3.)
    snapshot_dir = OUT / datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    snapshot_dir.mkdir(parents=True, exist_ok=False)
    manifest = []

    headers = {
        "Accept": "application/vnd.github+json",
        "X-GitHub-Api-Version": "2022-11-28",
    }

    # "with" opens one connection pool and closes it automatically at the end.
    with httpx.Client(headers=headers, timeout=30) as client:
        url = BASE
        page = 1
        while url:
            # TODO 2: page 1 needs PARAMS; every "next" URL already contains them
            # (plus the after= cursor), so sending them again would duplicate them.
            r = client.get(url, params=PARAMS if page == 1 else None)

            # Headers are strings; convert to int. Default to 0 if missing.
            remaining = int(r.headers.get("x-ratelimit-remaining", 0))

            # TODO 3: stop loudly on anything other than success.
            if r.status_code != 200:
                print(f"Page {page}: HTTP {r.status_code}, stopping.")
                print(r.text[:500])  # GitHub explains errors in the body
                break

            # TODO 4: save the body exactly as received. We write r.text (the raw
            # bytes decoded), not a re-dumped json object, so nothing is altered.
            records = r.json()
            (snapshot_dir / f"page_{page:03d}.json").write_text(r.text, encoding="utf-8")

            # TODO 5: one manifest row per page, so every file can be traced
            # back to the exact URL and moment it came from.
            manifest.append({
                "page": page,
                "url": str(r.url),
                "fetched_at": utc_now(),
                "status": r.status_code,
                "n_records": len(records),
                "ratelimit_remaining": remaining,
            })
            print(f"Page {page}: {len(records)} records, {remaining} requests left")

            # TODO 6: httpx parses the Link header into a dict for us.
            # .get(..., {}) avoids a KeyError on the last page, where there is no "next".
            url = r.links.get("next", {}).get("url")

            # TODO 7: rate limit guard, then a short pause.
            if url and remaining < MIN_REMAINING:
                print(f"Only {remaining} requests left; stopping early. Snapshot is incomplete.")
                break
            if url:
                time.sleep(PAUSE_SECONDS)

            page += 1

    # TODO 8: the manifest also records the run's parameters and whether it finished.
    run_info = {
        "base_url": BASE,
        "params": PARAMS,
        "started_folder": snapshot_dir.name,
        "finished_at": utc_now(),
        "complete": url is None,   # True only if we reached the last page
        "pages": manifest,
        "total_records": sum(p["n_records"] for p in manifest),
    }
    (snapshot_dir / "manifest.json").write_text(json.dumps(run_info, indent=2), encoding="utf-8")

    print(f"Saved {len(manifest)} pages, {run_info['total_records']} records to {snapshot_dir}")
    if not run_info["complete"]:
        print("WARNING: run did not reach the last page.")


if __name__ == "__main__":
    if len(sys.argv) > 1:
        PARAMS["published"] = sys.argv[1]
    fetch_all()
