"""Seedance (Dreamina) route — 공식 CLI. MVP: balance / estimate.
submit / wait / download 는 E3에서 추가 (지출 경로, 별도 승인)."""
import hashlib
import json
import re

from engine import dreamina
from engine.job import REF_RE

NAME = "seedance_cli"


def _spec_hash(shot, prompt):
    keys = ("model", "resolution", "ratio", "gen_sec")
    blob = json.dumps([prompt] + [shot.get(k) for k in keys], ensure_ascii=False)
    return hashlib.sha256(blob.encode("utf-8")).hexdigest()[:16]


def balance():
    return dreamina.balance()


def ensure_canvas(job, state):
    if state.get("canvas"):
        return state["canvas"]
    name = f"studio {state['episode']}"
    data = dreamina.call("canvas", "create", name)
    state["canvas"] = data["project"]["projectId"]
    state["canvas_url"] = data["project"].get("webUrl")
    state.save()
    return state["canvas"]


def ensure_asset(job, state, key):
    a = job["_assets"][key]
    cache = state.setdefault("uploads", {})
    if a["sha256"] in cache:
        return cache[a["sha256"]]
    data = dreamina.call("resource", "upload", "--project-id", state["canvas"], "--file", a["path"])
    rid = (data.get("resource") or data).get("resourceId")
    if not rid:
        raise RuntimeError(f"업로드 응답에 resourceId 없음: {str(data)[:300]}")
    cache[a["sha256"]] = rid
    state.save()
    return rid


def ensure_element(job, state, cast_key):
    """Element 노드는 캔버스 안에서만 참조 가능 (E0) → 리소스 ID로 이 캔버스에 0크레딧 재생성."""
    els = state.setdefault("elements", {})
    if cast_key in els:
        return els[cast_key]
    ref = job["cast"][cast_key]
    e = job["_elements"][ref][NAME]
    args = ["node", "create", "element", "--project-id", state["canvas"],
            "--title", e.get("title", ref), "--main", e["face_res"]]
    if e.get("voice_res"):
        args += ["--voice", e["voice_res"]]
    src = e.get("source_canvas")
    if src and src != state["canvas"]:
        for r in (e["face_res"], e.get("voice_res")):
            if r:
                args += ["--resource-source", f"{r}@{src}"]
    data = dreamina.call(*args)
    els[cast_key] = data["node"]["nodeId"]
    state.save()
    return els[cast_key]


def render_prompt(job, state, shot):
    refs = []

    def sub(m):
        kind, key = m.group(1), m.group(2)
        if kind == "cast":
            tok = f"node:{ensure_element(job, state, key)}"
        else:
            tok = f"res:{ensure_asset(job, state, key)}"
        if tok not in refs:
            refs.append(tok)
        return "{{" + tok + "}}"

    text = shot["prompt"]
    suffix = job["_preset"].get("dialogue_timing_suffix")
    if shot.get("line") and suffix and suffix not in text:
        text = text + " " + suffix
    return REF_RE.sub(sub, text), refs


def prepare(job, state, shot):
    """컷을 캔버스에 '저장만' 한다(생성 없음). 사양이 같으면 기존 노드 재사용."""
    ensure_canvas(job, state)
    prompt, refs = render_prompt(job, state, shot)
    h = _spec_hash(shot, prompt)
    rec = state.setdefault("shots", {}).get(shot["id"], {})
    if rec.get("node") and rec.get("spec") == h:
        return rec["node"]
    if rec.get("submit"):
        raise RuntimeError(f"{shot['id']}: 이미 제출된 컷의 사양이 바뀜 — 새 컷 ID로 추가하세요")
    args = ["node", "create", "video", "--project-id", state["canvas"],
            "--title", f"{shot['id']} {shot.get('speaker', '')}".strip(),
            "--mode", "m2v", "--model", shot["model"], "--resolution", shot["resolution"],
            "--ratio", shot["ratio"], "--duration", shot["gen_sec"], "--prompt", prompt]
    for r in refs:
        args += ["--ref", r]
    data = dreamina.call(*args)
    state["shots"][shot["id"]] = {"node": data["node"]["nodeId"], "spec": h}
    state.save()
    return data["node"]["nodeId"]


def estimate(job, state, shots):
    """컷 노드 저장 → node quote (읽기 전용). {shot_id: credits}, total 반환."""
    nodes = {s["id"]: prepare(job, state, s) for s in shots}
    args = ["node", "quote", "--project-id", state["canvas"]]
    for n in nodes.values():
        args += ["--node-id", n]
    data = dreamina.call(*args)
    by_node = {i["nodeId"]: i.get("maxCredits") for i in data["items"]}
    per = {sid: by_node.get(n) for sid, n in nodes.items()}
    return per, data.get("totalMaxCredits"), data.get("confirmationRequired")


# ─── E3: 지출 경로 (run --ceiling 승인 후에만 호출) ───
import uuid  # noqa: E402
from pathlib import Path  # noqa: E402


def submit(job, state, shots, ceiling):
    """승인 한도로 confirm → run. 제출 ID를 실행 전에 state에 고정(복구 시 재제출 금지)."""
    recs = [state["shots"][s["id"]] for s in shots]
    for s, r in zip(shots, recs):
        if r.get("submit"):
            raise RuntimeError(f"{s['id']}: 이미 제출됨({r['submit']}) — resume 사용")
        r["submit"] = str(uuid.uuid4())
        r["status"] = "submitting"
    state.save()
    nodes = [r["node"] for r in recs]
    args = ["node", "confirm", "--project-id", state["canvas"], "--credit-ceiling", ceiling]
    for n in nodes:
        args += ["--node-id", n]
    try:
        conf = dreamina.call(*args, allow_spend=True)
    except Exception:
        for r in recs:  # confirm 단계 실패 = run 미호출 → 제출 ID 회수
            r.pop("submit", None)
            r.pop("status", None)
        state.save()
        raise
    token = conf.get("creditConfirmationToken") or (conf.get("creditConfirmation") or {}).get("token")
    args = ["node", "run", "--project-id", state["canvas"]]
    if token:
        args += ["--credit-token", token]
    for n, r in zip(nodes, recs):
        args += ["--node-id", n, "--submit-id", r["submit"]]
    try:
        data = dreamina.call(*args, allow_spend=True)
    except dreamina.CliError as e:
        for r in recs:
            r["status"] = "uncertain"  # 응답 유실 가능 — 재실행 금지, resume로 조회
        state.save()
        raise
    for r in recs:
        r["status"] = "running"
    state["last_run"] = {"items": data.get("items")}
    state.save()
    return [r["submit"] for r in recs]


def wait_and_download(job, state, shot_id, dest_dir, timeout="15m"):
    r = state["shots"][shot_id]
    try:
        dreamina.call("operation", "wait", r["submit"], "--project-id", state["canvas"],
                      "--timeout", timeout, timeout=1200)
    except dreamina.CliError as e:
        if e.code == 20:
            return None  # 아직 진행 중
        r["status"] = "failed"
        r["error"] = (e.payload or {}).get("error")
        state.save()
        raise
    node = dreamina.call("node", "show", "--project-id", state["canvas"], "--node-id", r["node"])["nodes"][0]["node"]
    vids = [x for x in node.get("resources", []) if x["type"] == "video" and x.get("status") == "success"]
    if not vids:
        r["status"] = "failed"
        state.save()
        raise RuntimeError(f"{shot_id}: 완료됐으나 영상 리소스 없음")
    res = vids[-1]
    dest_dir = Path(dest_dir)
    dest_dir.mkdir(parents=True, exist_ok=True)
    out = dest_dir / f"{shot_id}_raw.mp4"
    dreamina.call("resource", "download", res["resourceId"], "--project-id", state["canvas"], "-o", str(out))
    r.update(status="done", resource=res["resourceId"], file=str(out),
             credits=res.get("creditsAmount"), video=res.get("video"))
    state.save()
    return out
