"""dreamina-canvas CLI 호출 래퍼. --yes 금지, 항상 json + non-interactive."""
import hashlib
import json
import os
import subprocess
from pathlib import Path

EXE = Path(os.environ.get("DREAMINA_CANVAS", Path.home() / "bin" / "dreamina-canvas.exe"))
CONTRACTS = Path(__file__).resolve().parent.parent / "contracts"
FORBIDDEN = {"--yes", "confirm", "run", "promote", "upscale", "interpolate", "delete"}
ALLOWED_SPEND = {("node", "confirm"), ("node", "run")}


class CliError(Exception):
    def __init__(self, args, code, payload):
        self.code, self.payload = code, payload
        err = (payload or {}).get("error", {})
        super().__init__(f"dreamina-canvas {' '.join(args[:3])} 실패 exit={code} {err.get('code')} {err.get('message')}")


def call(*args, allow_spend=False, timeout=600):
    args = [str(a) for a in args]
    if "--yes" in args:
        raise RuntimeError("--yes 금지")
    if FORBIDDEN & set(args[:2]) and not (allow_spend and tuple(args[:2]) in ALLOWED_SPEND):
        raise RuntimeError(f"지출·삭제 가능 명령 차단: {args[:2]} (E3 run 경로의 node confirm/run만 허용)")
    p = subprocess.run([str(EXE), "--format", "json", "--non-interactive", *args],
                       capture_output=True, timeout=timeout)
    out = p.stdout.decode("utf-8", "replace").strip()
    try:
        payload = json.loads(out) if out else None
    except json.JSONDecodeError:
        payload = {"raw": out[:2000]}
    if p.returncode != 0 or not (payload or {}).get("ok", False):
        raise CliError(args, p.returncode, payload)
    return payload["data"]


def balance():
    data = call("auth", "account")
    s = json.dumps(data)
    import re
    m = re.search(r'"availableCredits?"\s*:\s*"?(\d+)', s)
    return int(m.group(1)) if m else None


def schema_hash():
    p = subprocess.run([str(EXE), "schema", "--format", "json"], capture_output=True, timeout=120)
    return hashlib.sha256(p.stdout).hexdigest()


def pinned_schema_hash():
    f = CONTRACTS / "schema.json"
    return hashlib.sha256(f.read_bytes()).hexdigest() if f.exists() else None
