"""변형 추천 모듈 — 씬별 A/B 카메라 앵글/색감 변형 추천."""

import json
import logging
from pathlib import Path
from typing import Any, Dict, Optional

logger = logging.getLogger(__name__)

PROMPTS_DIR = (
    Path(__file__).resolve().parent.parent.parent.parent
    / "prompts" / "_base" / "variation_recommender" / "v1"
)

_RESPONSE_SCHEMA = {
    "type": "object",
    "properties": {
        "variation_a": {
            "type": "object",
            "properties": {
                "type": {
                    "type": "string",
                    "description": "angle | color | angle+color | none",
                },
                "angle": {
                    "type": ["object", "null"],
                    "properties": {
                        "horizontal": {"type": "number"},
                        "vertical": {"type": "number"},
                        "zoom": {"type": "number"},
                    },
                    "required": ["horizontal", "vertical", "zoom"],
                    "additionalProperties": False,
                    "description": "Angle params if type includes angle, else null",
                },
                "color": {
                    "type": "string",
                    "description": "Color/lighting prompt if type includes color, else empty",
                },
                "reason": {
                    "type": "string",
                    "description": "Why this variation is recommended",
                },
            },
            "required": ["type", "angle", "color", "reason"],
            "additionalProperties": False,
        },
        "variation_b": {
            "type": "object",
            "properties": {
                "type": {
                    "type": "string",
                    "description": "angle | color | angle+color | none",
                },
                "angle": {
                    "type": ["object", "null"],
                    "properties": {
                        "horizontal": {"type": "number"},
                        "vertical": {"type": "number"},
                        "zoom": {"type": "number"},
                    },
                    "required": ["horizontal", "vertical", "zoom"],
                    "additionalProperties": False,
                    "description": "Angle params if type includes angle, else null",
                },
                "color": {
                    "type": "string",
                    "description": "Color/lighting prompt if type includes color, else empty",
                },
                "reason": {
                    "type": "string",
                    "description": "Why this variation is recommended",
                },
            },
            "required": ["type", "angle", "color", "reason"],
            "additionalProperties": False,
        },
        "recommended": {
            "type": "string",
            "description": "Which variant to use as PDF default: original | A | B",
        },
        "reasoning": {
            "type": "string",
            "description": "Overall reasoning for the recommendation",
        },
    },
    "required": ["variation_a", "variation_b", "recommended", "reasoning"],
    "additionalProperties": False,
}


def _load_prompt(filename: str) -> str:
    """Load a prompt template file."""
    path = PROMPTS_DIR / filename
    if not path.exists():
        raise FileNotFoundError(f"Prompt file not found: {path}")
    return path.read_text(encoding="utf-8").strip()


class VariationRecommender:
    """씬별 A/B 변형(앵글/색감) 추천기.

    GPT-5.4를 사용해 씬 설명과 카메라/조명 정보를 분석하고
    최적의 A/B 변형을 추천한다.
    """

    def __init__(self, llm_client: Any, prompt_version: str = "v1") -> None:
        self._llm = llm_client
        self._version = prompt_version

    def recommend(
        self,
        scene_description: str,
        beat_title: str,
        camera_angle: str,
        lighting_mood: str,
    ) -> Dict[str, Any]:
        """Recommend A/B variations for a scene.

        Args:
            scene_description: Full scene description text.
            beat_title: Title of the scene beat.
            camera_angle: Current camera angle description.
            lighting_mood: Current lighting/mood description.

        Returns:
            {
                "variation_a": {
                    "type": "angle",
                    "angle": {"horizontal": 45, "vertical": 0, "zoom": 1.0},
                    "color": "",
                    "reason": "...",
                },
                "variation_b": {
                    "type": "color",
                    "angle": null,
                    "color": "warm golden sunset lighting",
                    "reason": "...",
                },
                "recommended": "A",
                "reasoning": "...",
            }
        """
        system_prompt = _load_prompt("system.md")
        user_template = _load_prompt("user.md")

        user_prompt = user_template.format(
            scene_description=scene_description,
            beat_title=beat_title,
            camera_angle=camera_angle,
            lighting_mood=lighting_mood,
        )

        result = self._llm.generate_structured(
            system_prompt=system_prompt,
            user_prompt=user_prompt,
            response_schema=_RESPONSE_SCHEMA,
            schema_name="variation_recommendation",
            max_tokens=4000,
        )

        return result
