#!/usr/bin/env python3
"""Tautoru teaching starter: list PCO versions and archive one selected XML source.

Python 3.10+, standard library only. Set PCO_API_KEY in the process environment.
  python3 pco_snapshot.py list fta
  python3 pco_snapshot.py list cga
  python3 pco_snapshot.py capture RETURNED_VERSION_ID

Source contract checked against https://api.legislation.govt.nz/docs/ on 2026-11-18.
Authenticated access is untested. This is source capture, not a graph importer or
an assessment of current law. No LLM is called. Files are saved under ./pco-sources.
Adapted from the source-discovery pattern in the supplied Tautoru NZ handover.
"""

import hashlib
import json
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timezone
from pathlib import Path

API = "https://api.legislation.govt.nz"
WORKS = {"fta": "act_public_1986_121", "cga": "act_public_1993_91"}
MAX_BYTES = 30_000_000


class CaptureError(Exception):
    """A safe error message containing no request headers or response bodies."""


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        # A redirect must never forward the API key to a different destination.
        return None


def download(url, *, key=None, expected="json"):
    parsed = urllib.parse.urlsplit(url)
    if (parsed.scheme != "https" or parsed.username or parsed.password
            or parsed.port not in (None, 443) or parsed.query or parsed.fragment):
        raise CaptureError("Expected a direct HTTPS source URL without a query or credentials.")
    if key is not None and parsed.netloc != "api.legislation.govt.nz":
        raise CaptureError("API credentials may only be sent to the PCO API origin.")
    if key is None and parsed.hostname not in ("www.legislation.govt.nz", "legislation.govt.nz"):
        raise CaptureError("This starter only downloads files from the official legislation website.")
    headers = {"Accept": "application/json" if expected == "json" else "application/xml"}
    if key is not None:
        headers["X-Api-Key"] = key
    request = urllib.request.Request(url, headers=headers)
    try:
        with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response:
            if response.status != 200:
                raise CaptureError("Source is not ready: a complete HTTP 200 response is required.")
            body = response.read(MAX_BYTES + 1)
            content_type = response.headers.get("Content-Type", "").lower()
    except urllib.error.HTTPError as error:
        if error.code == 429:
            raise CaptureError("PCO request quota reached. Wait for the service reset before retrying.") from None
        raise CaptureError(f"Source returned HTTP {error.code}. Check access and the documented endpoint.") from None
    except (urllib.error.URLError, TimeoutError, OSError):
        raise CaptureError("Source request failed or timed out. No snapshot was saved.") from None
    if not body.strip() or len(body) > MAX_BYTES:
        raise CaptureError("Source is empty or exceeds the starter's size limit.")
    prefix = body.lstrip()[:512].lower()
    if "text/html" in content_type or b"<!doctype html" in prefix or prefix.startswith(b"<html"):
        raise CaptureError("Received an HTML page instead of the requested source format.")
    if expected == "json" and "json" not in content_type:
        raise CaptureError("Expected a JSON response from the API.")
    return body


def api_json(path, key):
    if not key:
        raise CaptureError("Configure PCO_API_KEY in the process environment first.")
    try:
        data = json.loads(download(API + path, key=key))
    except (ValueError, UnicodeDecodeError):
        raise CaptureError("The API response is not valid JSON.") from None
    if not isinstance(data, dict):
        raise CaptureError("Unexpected API response shape.")
    return data


def list_versions(short_name, key):
    work_id = WORKS.get(short_name)
    if work_id is None:
        raise CaptureError("Choose fta or cga for this teaching example.")
    data = api_json(f"/v0/works/{work_id}/versions/", key)
    results = data.get("results")
    if not isinstance(results, list) or not all(isinstance(item, dict) for item in results):
        raise CaptureError("The API response has no usable version list.")
    # Preserve the response's pagination information. Do not claim full history.
    return {
        "work_id": work_id,
        "versions": [{"version_id": item.get("version_id"), "title": item.get("title")} for item in results],
        "page": data.get("page"), "per_page": data.get("per_page"), "total": data.get("total"),
        "note": "Returned page only. Select an exact identifier; no legal applicability is inferred.",
    }


def capture_version(version_id, key, output_root=Path("pco-sources")):
    # Keep the full returned ID, including date suffixes. Limit the starter to two Acts.
    pattern = r"(act_public_1986_121|act_public_1993_91)_en_\d{4}-\d{2}-\d{2}[A-Z]*"
    if not re.fullmatch(pattern, version_id):
        raise CaptureError("Use a returned version identifier for the Fair Trading or Consumer Guarantees Act.")
    version = api_json(f"/v0/versions/{urllib.parse.quote(version_id, safe='')}/", key)
    work_id = version_id.split("_en_")[0]
    if version.get("version_id") != version_id or version.get("work_id") != work_id:
        raise CaptureError("The API returned a different work or version.")
    formats = version.get("formats")
    if not isinstance(formats, list):
        raise CaptureError("The version has no usable format list.")
    xml_url = next((item.get("url") for item in formats
                    if isinstance(item, dict) and item.get("type") == "xml"), None)
    if not isinstance(xml_url, str):
        raise CaptureError("The selected version has no XML format link.")
    body = download(xml_url, expected="xml")  # Deliberately no API key on file requests.
    try:
        ET.fromstring(body)
    except ET.ParseError:
        raise CaptureError("The downloaded source is not well-formed XML.") from None
    fingerprint = hashlib.sha256(body).hexdigest()
    # Retain earlier bytes if the source later changes at the same version URL.
    folder = Path(output_root) / version_id / fingerprint
    manifest = {
        "work_id": work_id, "version_id": version_id, "title": version.get("title"),
        "source_url": xml_url, "captured_at": datetime.now(timezone.utc).isoformat(),
        "sha256": fingerprint, "bytes": len(body), "review_status": "unreviewed",
        "validation": "Well-formed XML only; source schema and extraction not validated.",
        "legal_applicability": "not_established", "graph_imported": False,
    }
    # The manifest is written last. Interrupted writes do not become a completed capture.
    folder.mkdir(parents=True, exist_ok=True)
    (folder / "source.xml").write_bytes(body)
    (folder / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
    return folder


def main():
    if len(sys.argv) != 3 or sys.argv[1] not in ("list", "capture"):
        print("Usage: python3 pco_snapshot.py list fta|cga\n"
              "       python3 pco_snapshot.py capture RETURNED_VERSION_ID", file=sys.stderr)
        return 2
    key = os.environ.get("PCO_API_KEY")
    try:
        if sys.argv[1] == "list":
            print(json.dumps(list_versions(sys.argv[2], key), indent=2))
        else:
            folder = capture_version(sys.argv[2], key)
            print(f"Saved an unreviewed source capture in {folder}")
        return 0
    except CaptureError as error:
        print(str(error), file=sys.stderr)
    except (OSError, ValueError):
        print("Capture could not complete. Check the source format and local storage.", file=sys.stderr)
    return 1


if __name__ == "__main__":
    sys.exit(main())
