"""Studio 영상 제작 실행기 (MVP: check, quote, run, resume).

  python studio_run.py check <episode_dir>
  python studio_run.py quote <episode_dir> [--shots C01,C02]
  python studio_run.py run <episode_dir> --ceiling N [--shots C01]
  python studio_run.py resume <episode_dir>

설계: scratch/bmad-studio-check/_bmad-output/planning-artifacts/video-pipeline/{PRD,ARCHITECTURE}.md
"""
import argparse
import datetime as dt
import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
sys.stdout.reconfigure(encoding="utf-8")

from engine import dreamina  # noqa: E402
from engine.job import JobError, load_job, validate  # noqa: E402
from engine.plan import plan_and_save  # noqa: E402
from engine.state import State  # noqa: E402
from routes import seedance_cli  # noqa: E402

ROUTES = {seedance_cli.NAME: seedance_cli}


def _checked(ep):
    job = load_job(ep)
    errors, warnings, shots = validate(job)
    for w in warnings:
        print(f"  경고  {w}")
    for e in errors:
        print(f"  거부  {e}")
    return job, errors, shots


def cmd_check(a):
    job, errors, shots = _checked(a.episode)
    if errors:
        print(f"check 실패: {len(errors)}건")
        return 1
    print(f"check 통과: {len(shots)}컷, 프리셋 {job['_preset']['name']}")
    for s in shots:
        print(f"  {s['id']:<5} {s['route']:<13} {s['model']} {s['resolution']} {s['gen_sec']}초"
              f"  {'대사' if s.get('line') else '무대사'}")
    return 0


def _select(shots, a):
    if getattr(a, "shots", None):
        want = a.shots.split(",")
        missing = set(want) - {s["id"] for s in shots}
        if missing:
            raise JobError(f"없는 컷: {sorted(missing)}")
        shots = [s for s in shots if s["id"] in want]
    return shots


def cmd_quote(a):
    job, errors, shots = _checked(a.episode)
    shots = _select(shots, a)
    if errors:
        print("check 실패 — 견적하지 않음")
        return 1
    if dreamina.schema_hash() != dreamina.pinned_schema_hash():
        print("  경고  CLI schema가 저장된 계약과 다름 (견적은 읽기 전용이라 계속, run은 거부 예정)")
    state = State(job["_ep_dir"])
    bal = None
    rows, total = [], 0
    for name in sorted({s["route"] for s in shots}):
        route = ROUTES[name]
        group = [s for s in shots if s["route"] == name]
        per, sub, need_confirm = route.estimate(job, state, group)
        bal = route.balance()
        for s in group:
            rows.append((s["id"], name, s["gen_sec"], per[s["id"]]))
        total += sub or 0
    out = {"at": dt.datetime.now().isoformat(timespec="seconds"), "canvas": state.get("canvas"),
           "balance": bal, "total": total,
           "shots": [{"id": i, "route": r, "gen_sec": g, "credits": c} for i, r, g, c in rows]}
    Path(job["_ep_dir"], "quote.json").write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"\n{'컷':<6}{'경로':<14}{'길이':>5}{'크레딧':>8}")
    for i, r, g, c in rows:
        print(f"{i:<6}{r:<14}{g:>4}s{c:>8}")
    print(f"{'합계':<24}{total:>9}   (잔액 {bal}, 크레딧 사용 0 — 견적만)")
    if state.get("canvas_url"):
        print(f"캔버스: {state['canvas_url']}")
    print(f"승인하려면: run --ceiling {total}" + (f" --shots {a.shots}" if a.shots else ""))
    return 0


def _ledger(ep, line):
    with open(Path(ep, "spend.log"), "a", encoding="utf-8") as f:
        f.write(line + "\n")


def cmd_run(a):
    import os
    job, errors, shots = _checked(a.episode)
    if errors:
        print("check 실패 — 실행하지 않음")
        return 1
    shots = _select(shots, a)
    if dreamina.schema_hash() != dreamina.pinned_schema_hash():
        print("중단: CLI schema가 저장된 계약(contracts/schema.json)과 다름 — 계약 재확인 후 실행")
        return 2
    state = State(job["_ep_dir"])
    lock = state.get("lock")
    if lock:
        print(f"중단: 실행 잠금 존재 {lock} — 다른 실행·워커 확인 후 사람이 --unlock")
        return 2
    route = ROUTES[shots[0]["route"]]
    if any(s["route"] != route.NAME for s in shots):
        print("중단: 한 번의 run은 경로 하나만")
        return 2
    per, total, _ = route.estimate(job, state, shots)
    print("재견적: " + ", ".join(f"{k} {v}" for k, v in per.items()) + f" = {total}")
    if total is None or total > a.ceiling:
        print(f"중단: 견적 {total} > 승인 한도 {a.ceiling} — 제출 0")
        return 3
    bal0 = route.balance()
    state["lock"] = {"pid": os.getpid(), "route": route.NAME,
                     "at": dt.datetime.now().isoformat(timespec="seconds")}
    state.save()
    now = dt.datetime.now().isoformat(timespec="seconds")
    try:
        subs = route.submit(job, state, shots, a.ceiling)
        for s, sub_id in zip(shots, subs):
            _ledger(job["_ep_dir"], f"{now} | {route.NAME} | {s['id']} | quote={per[s['id']]} ceiling={a.ceiling} | submitted | {sub_id}")
        print(f"제출: {len(subs)}컷 (잔액 시작 {bal0})")
        return _collect(job, state, route, [s["id"] for s in shots], bal0, total)
    finally:
        state.pop("lock", None)
        state.save()


def _collect(job, state, route, ids, bal0=None, total=None):
    clips = Path(job["_ep_dir"], "src", "assets", "clips")
    pending = []
    for sid in ids:
        out = route.wait_and_download(job, state, sid, clips)
        if out is None:
            pending.append(sid)
            print(f"  {sid}: 아직 생성 중 — 나중에 resume")
        else:
            print(f"  {sid}: 다운로드 {out}")
    bal1 = route.balance()
    if bal0 is not None:
        used = bal0 - bal1
        note = "" if total is None or used == total or pending else f"  ⚠ 견적 {total}과 다름"
        _ledger(job["_ep_dir"], f"{dt.datetime.now().isoformat(timespec='seconds')} | {route.NAME} | {','.join(ids)} | quote={total} | actual={used} (잔액 {bal0}->{bal1}){note}")
        print(f"실제 차감 {used} (잔액 {bal0} → {bal1}){note}")
    print("상태: 생성 완료 · 션 시청·청취 판정 대기" if not pending else f"대기 중: {pending}")
    return 0 if not pending else 20


def cmd_resume(a):
    job = load_job(a.episode)
    validate(job)
    state = State(job["_ep_dir"])
    ids = [k for k, v in state.get("shots", {}).items() if v.get("submit") and v.get("status") != "done"]
    if not ids:
        print("회수할 제출 없음")
        return 0
    print(f"재제출 없이 조회만: {ids}")
    return _collect(job, state, ROUTES[seedance_cli.NAME], ids)


def cmd_unlock(a):
    state = State(Path(a.episode).resolve())
    print(f"잠금 해제: {state.pop('lock', None)}")
    state.save()
    return 0


def cmd_plan(a):
    jp = Path(a.output_dir) / "job.json"
    if jp.exists() and not a.force:
        print(f"거부: job.json 이미 존재 ({jp}) — 덮어쓰려면 --force")
        return 1
    shots_filter = a.shots.split(",") if getattr(a, "shots", None) else None
    plan_and_save(
        storyboard_path=a.storyboard,
        output_dir=a.output_dir,
        work=a.work,
        shots_filter=shots_filter,
        force=a.force,
    )
    return cmd_check(argparse.Namespace(episode=a.output_dir))


def main():
    ap = argparse.ArgumentParser(prog="studio_run")
    sub = ap.add_subparsers(dest="cmd", required=True)
    for name, fn in (("check", cmd_check), ("quote", cmd_quote), ("run", cmd_run),
                     ("resume", cmd_resume), ("unlock", cmd_unlock)):
        p = sub.add_parser(name)
        p.add_argument("episode")
        if name in ("quote", "run"):
            p.add_argument("--shots")
        if name == "run":
            p.add_argument("--ceiling", type=int, required=True)
        p.set_defaults(fn=fn)
    p_plan = sub.add_parser("plan")
    p_plan.add_argument("storyboard")
    p_plan.add_argument("output_dir")
    p_plan.add_argument("--work", required=True)
    p_plan.add_argument("--shots")
    p_plan.add_argument("--force", action="store_true")
    p_plan.set_defaults(fn=cmd_plan)
    a = ap.parse_args()
    try:
        return a.fn(a)
    except (JobError, dreamina.CliError, RuntimeError) as e:
        print(f"중단: {e}")
        return 2


if __name__ == "__main__":
    sys.exit(main())
