#!/usr/bin/env python3
import hashlib
import json
import os
from pathlib import Path

PROJECT = Path(__file__).resolve().parents[1]
AUTHORITY = PROJECT / "script/workflow-copy-authority.json"
INTRO_SOURCE = PROJECT / "audio/intro-voice-source.txt"
RECEIPT = PROJECT / "log/workflow-copy-materialization.json"


def sha(data):
    return hashlib.sha256(data).hexdigest()


def main():
    authority = json.loads(AUTHORITY.read_text(encoding="utf-8"))
    text = authority.get("spoken_intro", {}).get("exact_text")
    if authority.get("approval_state") != "locked" or not isinstance(text, str) or not text.endswith("\n"):
        raise RuntimeError("locked workflow-copy authority is invalid")
    data = text.encode("utf-8")
    if authority["spoken_intro"].get("sha256") != sha(data):
        raise RuntimeError("spoken intro authority hash mismatch")
    INTRO_SOURCE.parent.mkdir(parents=True, exist_ok=True)
    temp = INTRO_SOURCE.with_name(INTRO_SOURCE.name + ".part")
    temp.write_bytes(data)
    os.replace(temp, INTRO_SOURCE)
    receipt = {
        "version": 1,
        "verified": INTRO_SOURCE.read_bytes() == data,
        "workflow_copy_authority_path": "script/workflow-copy-authority.json",
        "workflow_copy_authority_sha256": sha(AUTHORITY.read_bytes()),
        "intro_source_path": "audio/intro-voice-source.txt",
        "intro_source_sha256": sha(INTRO_SOURCE.read_bytes()),
    }
    temp = RECEIPT.with_name(RECEIPT.name + ".part")
    temp.write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    os.replace(temp, RECEIPT)
    print(json.dumps(receipt, ensure_ascii=False))
    return 0 if receipt["verified"] else 1


if __name__ == "__main__":
    raise SystemExit(main())
