#!/usr/bin/env python3
"""Snapshot and validate writer artifacts only after authoritative completion.

The caller must supply --completion-receipt from the worker/delegation. Merely seeing
an output path is never completion evidence.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import subprocess
from pathlib import Path


def sha256(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--completion-receipt", type=Path, required=True)
    ap.add_argument("--artifact", type=Path, action="append", required=True)
    ap.add_argument("--validator", type=Path, required=True)
    ap.add_argument("--snapshot-dir", type=Path, required=True)
    ap.add_argument("--receipt", type=Path, required=True)
    args = ap.parse_args()

    completion = json.loads(args.completion_receipt.read_text())
    if completion.get("status") not in {"completed", "passed"}:
        raise SystemExit("authoritative completion receipt is not terminal-success")

    args.snapshot_dir.mkdir(parents=True, exist_ok=True)
    finalized = []
    for source in args.artifact:
        raw = source.read_bytes()
        parsed = json.loads(raw)
        digest = sha256(raw)
        snapshot = args.snapshot_dir / f"{source.stem}_final_{digest[:12]}.json"
        snapshot.write_bytes(raw)
        if sha256(snapshot.read_bytes()) != digest:
            raise SystemExit(f"snapshot checksum mismatch: {source}")

        check = subprocess.run(
            ["python3", str(args.validator), str(snapshot)],
            text=True,
            capture_output=True,
        )
        if check.returncode:
            raise SystemExit(f"validation failed: {snapshot}\n{check.stdout}\n{check.stderr}")
        if sha256(snapshot.read_bytes()) != digest:
            raise SystemExit(f"snapshot changed during validation: {snapshot}")

        finalized.append(
            {
                "source": str(source),
                "snapshot": str(snapshot),
                "sha256": digest,
                "parsed_identity": {
                    "project_id": parsed.get("project_id"),
                    "title": parsed.get("title"),
                    "part_range": parsed.get("part_range"),
                },
                "validation": json.loads(check.stdout),
            }
        )

    result = {
        "status": "passed",
        "authoritative_completion_receipt": str(args.completion_receipt),
        "artifacts": finalized,
    }
    args.receipt.parent.mkdir(parents=True, exist_ok=True)
    args.receipt.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
    print(json.dumps(result, ensure_ascii=False))


if __name__ == "__main__":
    main()
