#!/usr/bin/env python3
from __future__ import annotations

import hashlib
import json
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
PROMPT_PATH = ROOT / "image/right-panel-recovery-prompt.json"
OUTPUT = ROOT / "image/right-panel-master-v2.png"
GENERATOR = Path("/home/hermes/.hermes/skills/content-creation/tao-anh/scripts/generate_image.py")


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


def main() -> int:
    prompt_doc = json.loads(PROMPT_PATH.read_text(encoding="utf-8"))
    if prompt_doc.get("image_api_called") is not False:
        raise RuntimeError("recovery prompt is not virgin")
    if OUTPUT.exists():
        raise RuntimeError(f"recovery output already exists: {OUTPUT}")
    completed = subprocess.run([
        sys.executable, str(GENERATOR), "--prompt", prompt_doc["prompt"],
        "--output", str(OUTPUT), "--n", "1", "--detail", "high",
        "--format", "png", "--timeout", "600",
    ], text=True, capture_output=True, timeout=660)
    if completed.returncode != 0 or not OUTPUT.is_file() or OUTPUT.stat().st_size <= 1024:
        raise RuntimeError(f"right-panel recovery failed: exit={completed.returncode}; stderr={completed.stderr[-2000:]}")
    if OUTPUT.read_bytes()[:8] != b"\x89PNG\r\n\x1a\n":
        raise RuntimeError("right-panel recovery output is not PNG")
    receipt = {
        "status": "completed_pending_visual_review", "verified": False,
        "source_artifact": prompt_doc.get("source_artifact"), "source_sha256": prompt_doc.get("source_sha256"),
        "prompt_path": str(PROMPT_PATH), "prompt_sha256": sha256(PROMPT_PATH),
        "output_path": str(OUTPUT), "output_sha256": sha256(OUTPUT), "output_bytes": OUTPUT.stat().st_size,
        "image_api_called": True,
    }
    receipt_path = ROOT / "log/right-panel-artwork-recovery-v2.json"
    receipt_path.write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"status": receipt["status"], "verified": False, "output": str(OUTPUT), "receipt": str(receipt_path)}, ensure_ascii=False))
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as exc:
        print(json.dumps({"status": "failed", "verified": False, "error": f"{type(exc).__name__}: {exc}"}, ensure_ascii=False))
        raise SystemExit(1)
