"""storyboard.json -> job.json 변환기 (E1b)."""
import datetime as dt
import json
import re
from pathlib import Path

from engine.job import JobError, load_elements, load_preset, min_gen_sec, sha256


class PlanError(JobError):
    pass


def build_alias_map(elements):
    alias_map = {}
    for key, data in elements.items():
        if key.startswith("_"):
            continue
        for alias in data.get("aliases", []):
            alias_map[alias] = key
        alias_map[key] = key
        if "name" in data:
            alias_map[data["name"]] = key
    return alias_map


def plan(storyboard_path, work="mugi-yeo", shots_filter=None, preset_name="drama"):
    """storyboard.json을 읽어 (job_dict, warnings)를 반환한다."""
    sb_path = Path(storyboard_path).resolve()
    if not sb_path.exists():
        raise PlanError(f"storyboard 파일 없음: {sb_path}")

    ep_dir = sb_path.parent
    storyboard = json.loads(sb_path.read_text(encoding="utf-8"))
    preset = load_preset(preset_name)
    elements = load_elements(work)
    if not elements:
        raise PlanError(f"elements.json 없음: work={work}")
    alias_map = build_alias_map(elements)

    raw_shots = storyboard.get("shots", [])
    if shots_filter:
        want = shots_filter if isinstance(shots_filter, (list, tuple, set)) else shots_filter.split(",")
        existing_ids = {s.get("id") for s in raw_shots}
        missing = set(want) - existing_ids
        if missing:
            raise PlanError(f"없는 컷: {sorted(missing)}")
        raw_shots = [s for s in raw_shots if s.get("id") in want]

    used_cast = set()
    assets = {}
    converted_shots = []
    warnings = []

    for s in raw_shots:
        sid = s.get("id", "?")
        kind = s.get("kind")
        if kind == "voice_source":
            warnings.append(f"{sid}: 영상 아님, 건너뜀")
            continue
        if kind not in ("dialogue", "silent"):
            warnings.append(f"{sid}: 알 수 없는 kind '{kind}', 건너뜀")
            continue

        # 필수 필드 검사
        camera = s.get("camera")
        action = s.get("action")
        if not camera or not str(camera).strip():
            raise PlanError(f"{sid}: camera 비어 있음")
        if not action or not str(action).strip():
            raise PlanError(f"{sid}: action 비어 있음")

        if kind == "dialogue":
            spk_raw = s.get("speaker")
            line = s.get("line_for_prompt")
            if not spk_raw or not str(spk_raw).strip():
                raise PlanError(f"{sid}: 대사 컷 speaker 비어 있음")
            if not line or not str(line).strip():
                raise PlanError(f"{sid}: 대사 컷 line_for_prompt 비어 있음")
            if spk_raw not in alias_map:
                raise PlanError(f"{sid}: 매칭되지 않는 화자 '{spk_raw}'")
            speaker_key = alias_map[spk_raw]
            used_cast.add(speaker_key)
        else:
            speaker_key = None
            line = None

        # 등장 인물 매칭
        char_keys = []
        for c in s.get("characters", []):
            if c not in alias_map:
                raise PlanError(f"{sid}: 매칭되지 않는 인물 '{c}'")
            k = alias_map[c]
            if k not in char_keys:
                char_keys.append(k)
            used_cast.add(k)

        # 배경 / 시작 이미지
        start_img = s.get("start_image")
        asset_key = None
        if start_img:
            img_path = (ep_dir / "src" / "assets" / "visuals" / start_img).resolve()
            if not img_path.exists():
                raise PlanError(f"{sid}: 시작 이미지 파일 없음 {img_path}")
            asset_key = Path(start_img).stem
            if asset_key not in assets:
                digest = sha256(img_path)
                assets[asset_key] = {"path": str(img_path.as_posix()), "sha256": digest}

        # 길이 결정
        if kind == "dialogue":
            speech = round(len(re.sub(r"\s", "", line)) / preset["syllables_per_sec"], 2)
            need = min_gen_sec(speech, preset)
            target = s.get("generation_seconds_target")
            if target is not None and target > need:
                gen_sec = target
            else:
                gen_sec = None
        else:
            target = s.get("generation_seconds_target")
            if target is None:
                target = preset.get("default_silent_sec", 5)
            if target < 4:
                warnings.append(f"{sid}: 무대사 길이 {target}초 < 4초 → 4초로 상향")
                gen_sec = 4
            else:
                gen_sec = target

        # 프롬프트 조립
        prompt_parts = []
        if asset_key:
            prompt_parts.append(f"{{asset:{asset_key}}} 의 장면.")

        if char_keys:
            char_items = [f"{{cast:{k}}} {elements[k].get('desc_ko', '')}".strip() for k in char_keys]
            char_str = " ".join(char_items)
            if not char_str.endswith("."):
                char_str += "."
            prompt_parts.append(char_str)

        cam_str = str(camera).strip().rstrip(".")
        action_str = str(action).strip()
        if not action_str.endswith((".", "!", "?")):
            action_str += "."
        prompt_parts.append(f"카메라: {cam_str}. {action_str}")

        if kind == "dialogue":
            prompt_parts.append(
                f"{{cast:{speaker_key}}} 가 한국어로 말한다: '{line}' 등록된 목소리로 말한다. 대사 외 임의 발화 없음."
            )
        else:
            prompt_parts.append("아무도 말하지 않는다. 입을 편안히 다문다.")

        prompt_parts.append("실사 한국 드라마 톤. 모든 대사는 한국어. 화면에 글자·자막·간판 글씨 없음.")
        prompt = " ".join(prompt_parts)

        # 컷 구성
        shot_entry = {
            "id": sid,
            "source": {"storyboard_id": s.get("id"), "scene": s.get("scene")},
        }
        if kind == "dialogue":
            shot_entry["speaker"] = speaker_key
            shot_entry["line"] = line
        if gen_sec is not None:
            shot_entry["gen_sec"] = gen_sec
        shot_entry["prompt"] = prompt

        converted_shots.append(shot_entry)

    # 렌즈/빛/색감 미기재 요약 경고
    if converted_shots:
        warnings.append(f"{len(converted_shots)}컷: 렌즈·빛·색감 미기재")

    now_iso = dt.datetime.now().isoformat(timespec="seconds")
    cast_dict = {k: k for k in sorted(used_cast)}

    job = {
        "schema": 1,
        "work": work,
        "preset": preset_name,
        "set": None,
        "note": f"storyboard {sb_path.as_posix()} 변환 ({now_iso})",
        "cast": cast_dict,
        "assets": assets,
        "shots": converted_shots,
    }

    return job, warnings


def plan_and_save(storyboard_path, output_dir, work="mugi-yeo", shots_filter=None, force=False):
    """storyboard를 변환해 output_dir/job.json에 저장한다."""
    out_dir = Path(output_dir).resolve()
    jp = out_dir / "job.json"
    if jp.exists() and not force:
        raise PlanError(f"job.json 이미 존재: {jp} (--force 필요)")

    job, warnings = plan(storyboard_path, work=work, shots_filter=shots_filter)
    for w in warnings:
        print(f"  경고  {w}")

    out_dir.mkdir(parents=True, exist_ok=True)
    jp.write_text(json.dumps(job, ensure_ascii=False, indent=2), encoding="utf-8")
    return jp
