#!/usr/bin/env python3
"""Stamp the check artifact with the exact input tree it attests.

The tree hash is the key `reuse_verdicts.py` looks up; the reused-from
pointer keeps provenance honest when a judgment is inherited. The
instrument's doc gains `sha` / `tree` / `verdicts_reused_from_run` as
workflow provenance — the risk-walk content itself is untouched.

No-ops (exit 0) when there is no artifact this run — nothing to stamp.

Usage:
    stamp_artifact.py

Environment:
    GITHUB_SHA    the run's commit sha (required)
    REUSED_FROM   run id the verdicts were reused from (optional)

Stdlib only; reads/writes `dds-check.json` in the working directory.
"""

import json
import os
import subprocess

DOC_NAME = "dds-check.json"


def main():
    try:
        doc = json.load(open(DOC_NAME))
    except (OSError, json.JSONDecodeError):
        raise SystemExit(0)  # no artifact this run — nothing to stamp

    doc["sha"] = os.environ["GITHUB_SHA"]
    doc["tree"] = subprocess.run(
        ["git", "rev-parse", "HEAD^{tree}"],
        capture_output=True,
        text=True,
    ).stdout.strip()
    if os.environ.get("REUSED_FROM"):
        doc["verdicts_reused_from_run"] = int(os.environ["REUSED_FROM"])

    json.dump(doc, open(DOC_NAME, "w"), indent=1)


if __name__ == "__main__":
    main()
