#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
=============================================================================
TEST START FRAME STRATEGY & CHARACTER TURNAROUND VIEWS INTEGRATION
=============================================================================
Kiểm thử tự động ma trận định tuyến Start Frame:
1. find_character_turnaround_view tìm đúng file ảnh crop trong views/
2. classify_start_frame_strategy phân định chính xác 4 chiến lược:
   - CHARACTER_TURNAROUND_VIEW (Close-up, MCU, Portrait, Entrance cut)
   - GEMINI_BANANA_KEYFRAME (Wide, Establishing, Multi-character, Environment)
   - HEAD_TAIL_PREV_FRAME (Continuous take)
   - TEXT_TO_VIDEO (Text-to-video / Prologue opener)
3. resolve_start_frame_v3 trả về bộ 3 giá trị (path, take_type, strategy)
=============================================================================
"""

import sys
from pathlib import Path
import pytest

PROJECT_ROOT = Path(__file__).resolve().parent.parent
PIPELINE_DIR = PROJECT_ROOT / "05_Production_Pipeline"
if str(PIPELINE_DIR) not in sys.path:
    sys.path.insert(0, str(PIPELINE_DIR))

import production_orchestrator as po


class TestCharacterTurnaroundViewsLookup:
    """Kiểm thử tra cứu ảnh góc nhìn Character Turnaround Sheet."""

    def test_find_turnaround_portrait_views(self):
        for char_key in ["thuy_kieu", "thuy_van", "kim_trong", "vuong_quan", "vuong_ong", "vuong_ba", "dam_tien"]:
            view_path = po.find_character_turnaround_view(char_key, "portrait")
            assert view_path is not None, f"Không tìm thấy portrait view cho nhân vật: {char_key}"
            assert view_path.exists(), f"File portrait view không tồn tại: {view_path}"
            assert "views" in view_path.parts
            assert "portrait" in view_path.name

    def test_find_turnaround_front_views(self):
        for char_key in ["thuy_kieu", "kim_trong", "vuong_quan"]:
            view_path = po.find_character_turnaround_view(char_key, "front")
            assert view_path is not None, f"Không tìm thấy front view cho nhân vật: {char_key}"
            assert view_path.exists(), f"File front view không tồn tại: {view_path}"
            assert "views" in view_path.parts
            assert "front" in view_path.name


class TestStartFrameStrategyMatrix:
    """Kiểm thử ma trận phân loại chiến lược Start Frame."""

    def test_wide_establishing_classified_as_banana_keyframe(self):
        shot_data = {
            "scene_title": "Toàn cảnh phòng khách họ Vương - Wide Establishing Shot",
            "motion_prompt": "Cảnh toàn phòng khách trang nghiêm, Vương Ông và Vương Bà đàm đạo trà mai",
            "character_anchor": "vuong_ong + vuong_ba"
        }
        strat, vtype = po.classify_start_frame_strategy("ep01_scene02_shot01", shot_data, take_type="CINEMATIC_CUT")
        assert strat == "GEMINI_BANANA_KEYFRAME"
        assert vtype is None

    def test_close_up_classified_as_turnaround_portrait(self):
        shot_data = {
            "scene_title": "Cận cảnh Vương Ông ân cần căn dặn (Close-Up Vương Ông)",
            "motion_prompt": "Cận cảnh gương mặt Vương Ông đôn hậu, ánh mắt ấm áp căn dặn",
            "character_anchor": "vuong_ong"
        }
        strat, vtype = po.classify_start_frame_strategy("ep01_scene02_shot10", shot_data, take_type="CINEMATIC_CUT")
        assert strat == "CHARACTER_TURNAROUND_VIEW"
        assert vtype == "portrait"

    def test_entrance_classified_as_turnaround_front(self):
        shot_data = {
            "scene_title": "Vương Quan bước vào bái chào (Medium Shot Entrance)",
            "motion_prompt": "Vương Quan bước vào bái chào cha mẹ, phong thái thiếu niên",
            "character_anchor": "vuong_quan"
        }
        strat, vtype = po.classify_start_frame_strategy("ep01_scene02_shot08", shot_data, take_type="CINEMATIC_CUT")
        assert strat == "CHARACTER_TURNAROUND_VIEW"
        assert vtype == "front"

    def test_continuous_take_classified_as_head_tail(self):
        shot_data = {
            "scene_title": "Tiếp diễn chuyển động",
            "character_anchor": "kim_trong"
        }
        strat, vtype = po.classify_start_frame_strategy(
            "ep01_scene07_shot02",
            shot_data,
            take_type="CONTINUOUS_TAKE",
            resolved_path="04_Assets/keyframes/ep01_scene07_shot01/clean_frame_239.jpg"
        )
        assert strat == "HEAD_TAIL_PREV_FRAME"
        assert vtype is None


class TestResolveStartFrameV3Contract:
    """Kiểm thử hợp đồng trả về của resolve_start_frame_v3."""

    def test_v3_returns_tuple_of_three(self):
        all_shots = po.get_all_shots()
        sdata = all_shots.get("ep01_scene02_shot10", {})
        res_path, take_type, strat = po.resolve_start_frame_v3("ep01_scene02_shot10", sdata)
        assert res_path is not None
        assert take_type == "CINEMATIC_CUT"
        assert strat == "CHARACTER_TURNAROUND_VIEW"
        assert "vuong_ong" in res_path.lower()

    def test_v3_explicit_turnaround_view_resolves_to_cropped_file(self):
        all_shots = po.get_all_shots()
        sdata = all_shots.get("ep01_scene02_shot10", {}).copy()
        sdata["turnaround_view"] = "portrait"
        res_path, take_type, strat = po.resolve_start_frame_v3("ep01_scene02_shot10", sdata)
        assert res_path is not None
        assert "views" in res_path
        assert "portrait" in res_path
        assert Path(res_path).exists()


if __name__ == "__main__":
    pytest.main([__file__, "-v"])
