import json
import shutil
import sys
import tempfile
import unittest
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))

from engine.plan import PlanError, plan


class TestPlan(unittest.TestCase):
    def setUp(self):
        self.temp_dir = Path(tempfile.mkdtemp())
        self.sb_file = self.temp_dir / "storyboard.json"

    def tearDown(self):
        shutil.rmtree(self.temp_dir)

    def _write_storyboard(self, shots):
        data = {
            "title": "테스트 스토리보드",
            "shots": shots,
        }
        self.sb_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")

    def test_skip_narration(self):
        """1. 내레이션(voice_source) 건너뜀 및 경고 테스트"""
        shots = [
            {
                "id": "N1",
                "scene": "내레이션 음성 소스",
                "kind": "voice_source",
                "camera": "미디엄 클로즈업, 고정",
                "action": "아름이 카메라 옆을 보며 말한다.",
                "speaker": "송아름",
                "line_for_prompt": "나는 아름이다.",
                "characters": ["무기_아름"],
                "start_image": None,
            },
            {
                "id": "A01",
                "scene": "씬 1",
                "kind": "silent",
                "camera": "와이드 샷, 고정",
                "action": "아름이 서 있다.",
                "characters": ["무기_아름"],
                "start_image": None,
                "generation_seconds_target": 5,
            },
        ]
        self._write_storyboard(shots)
        job, warnings = plan(self.sb_file, work="mugi-yeo")
        shot_ids = [s["id"] for s in job["shots"]]
        self.assertNotIn("N1", shot_ids)
        self.assertIn("A01", shot_ids)
        self.assertTrue(any("N1: 영상 아님, 건너뜀" in w for w in warnings))

    def test_unmatched_character_error(self):
        """2. 미매칭 인물 오류 테스트"""
        shots = [
            {
                "id": "X01",
                "scene": "씬 1",
                "kind": "silent",
                "camera": "와이드 샷, 고정",
                "action": "외계인이 등장한다.",
                "characters": ["외계인_철수"],
                "start_image": None,
                "generation_seconds_target": 5,
            }
        ]
        self._write_storyboard(shots)
        with self.assertRaises(PlanError) as ctx:
            plan(self.sb_file, work="mugi-yeo")
        self.assertIn("매칭되지 않는 인물 '외계인_철수'", str(ctx.exception))

    def test_dialogue_line_in_prompt(self):
        """3. 대사 line이 프롬프트에 그대로 포함되는지 테스트"""
        test_line = "반갑습니다. 오늘 점심 메뉴는 돈까스입니다."
        shots = [
            {
                "id": "D01",
                "scene": "씬 1",
                "kind": "dialogue",
                "camera": "바스트 샷, 고정",
                "action": "아름이 미소를 지으며 말한다.",
                "speaker": "송아름",
                "line_for_prompt": test_line,
                "characters": ["무기_아름"],
                "start_image": None,
                "generation_seconds_target": 5,
            }
        ]
        self._write_storyboard(shots)
        job, _ = plan(self.sb_file, work="mugi-yeo")
        self.assertEqual(len(job["shots"]), 1)
        shot = job["shots"][0]
        self.assertEqual(shot["line"], test_line)
        self.assertIn(test_line, shot["prompt"])
        self.assertIn("{cast:areum} 가 한국어로 말한다:", shot["prompt"])

    def test_silent_under_4s_raised_to_4(self):
        """4. 무대사 4초 미만은 4초로 상향 및 경고 테스트"""
        shots = [
            {
                "id": "S01",
                "scene": "씬 1",
                "kind": "silent",
                "camera": "벽시계 인서트, 고정",
                "action": "시계 초침이 움직인다.",
                "characters": [],
                "start_image": None,
                "generation_seconds_target": 2,
            }
        ]
        self._write_storyboard(shots)
        job, warnings = plan(self.sb_file, work="mugi-yeo")
        self.assertEqual(len(job["shots"]), 1)
        shot = job["shots"][0]
        self.assertEqual(shot["gen_sec"], 4)
        self.assertTrue(any("S01: 무대사 길이 2초 < 4초 → 4초로 상향" in w for w in warnings))


if __name__ == "__main__":
    unittest.main()
