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

ROOT = Path(__file__).resolve().parents[1]
PROMPTS = ROOT / "image/prompts.json"
GENERATOR = Path.home() / ".hermes/skills/content-creation/tao-anh/scripts/generate_image.py"
RECEIPT = ROOT / "log/artwork-generation.json"
TARGETS = {
    "intro": ROOT / "image/intro-poster-1920x1080.png",
    "right_panel": ROOT / "image/right-panel-master.png",
    "left_panel": ROOT / "image/left-panel-master.png",
}


def sha256(path):
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for block in iter(lambda: handle.read(8 * 1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def atomic_json(path, data):
    temp = path.with_suffix(path.suffix + ".part")
    temp.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    os.replace(temp, path)


def check_png(path):
    if not path.is_file() or path.stat().st_size <= 8:
        raise RuntimeError(f"missing or empty image: {path}")
    with path.open("rb") as handle:
        if handle.read(8) != b"\x89PNG\r\n\x1a\n":
            raise RuntimeError(f"not PNG: {path}")


def main():
    bundle = json.loads(PROMPTS.read_text(encoding="utf-8"))
    for rel, expected in bundle["source_authority_hashes"].items():
        path = ROOT / rel
        if sha256(path) != expected:
            raise RuntimeError(f"authority drift: {rel}")
    if any(path.exists() for path in TARGETS.values()) or RECEIPT.exists():
        raise RuntimeError("artwork output/receipt must be virgin")
    results = {}
    for key, output in TARGETS.items():
        subprocess.run(
            ["python3", str(GENERATOR), "--prompt", bundle["prompts"][key], "--output", str(output), "--n", "1", "--detail", "high", "--format", "png", "--timeout", "600"],
            check=True,
        )
        check_png(output)
        for rel, expected in bundle["source_authority_hashes"].items():
            if sha256(ROOT / rel) != expected:
                raise RuntimeError(f"authority drift after provider call: {rel}")
        results[key] = {"path": str(output.relative_to(ROOT)), "sha256": sha256(output), "bytes": output.stat().st_size}
        atomic_json(RECEIPT, {"status": "running", "verified": False, "provider": "cx/gpt-5.5-image", "source_authority_hashes": bundle["source_authority_hashes"], "results": results, "updated_at": datetime.datetime.now(datetime.timezone.utc).isoformat()})
    now = datetime.datetime.now(datetime.timezone.utc).isoformat()
    atomic_json(RECEIPT, {"status": "completed", "verified": True, "provider": "cx/gpt-5.5-image", "source_authority_hashes": bundle["source_authority_hashes"], "results": results, "completed_at": now})
    bundle["image_api_called"] = True
    bundle["generation_receipt"] = str(RECEIPT.relative_to(ROOT))
    bundle["updated_at"] = now
    atomic_json(PROMPTS, bundle)
    print(json.dumps({"status": "completed", "targets": results}, ensure_ascii=False))


if __name__ == "__main__":
    main()
