"""스타일 규칙 생성 모듈 — 시나리오 분석 후 T2I에 적용할 규칙을 LLM이 생성."""

import json
from typing import Any, Dict, Optional

from app.modules.llm.llm_client import call_structured
from app.modules.prompt_loader import load_prompt

STYLE_RULES_SCHEMA: Dict[str, Any] = {
    "type": "object",
    "additionalProperties": False,
    "properties": {
        "era": {"type": "string", "description": "시대 배경 (현대, 근미래, 중세 등)"},
        "region": {"type": "string", "description": "국가/지역 (한국, 일본, 우주 등)"},
        "genre_tone": {"type": "string", "description": "장르 톤 (리얼리즘, SF, 판타지 등)"},
        "architecture_style": {"type": "string", "description": "건축/환경 스타일 키워드"},
        "costume_style": {"type": "string", "description": "의상 스타일 키워드"},
        "tech_level": {"type": "string", "description": "기술 수준"},
        "must_maintain": {
            "type": "array",
            "items": {"type": "string"},
            "description": "반드시 유지할 시각적 규칙 목록",
        },
        "must_avoid": {
            "type": "array",
            "items": {"type": "string"},
            "description": "반드시 금지할 시각적 요소 목록",
        },
        "color_mood": {"type": "string", "description": "전체 색감/분위기 톤"},
        "aspect_ratio": {"type": "string", "description": "권장 이미지 비율"},
    },
    "required": [
        "era", "region", "genre_tone", "architecture_style",
        "costume_style", "tech_level", "must_maintain", "must_avoid",
        "color_mood", "aspect_ratio",
    ],
}


def generate_style_rules(
    fulltext: str,
    language: str = "ko",
    project_llm_config: Optional[Dict] = None,
) -> Dict[str, Any]:
    """시나리오 전문을 분석하여 T2I 스타일 규칙을 생성.

    Returns:
        {"era": "...", "must_maintain": [...], "must_avoid": [...], ...}
    """
    system_prompt = load_prompt("scene_generator", "style_rules_generator")

    # CLAUDE.md 절대 규칙: 시나리오 텍스트를 자르지 마라. 전문 그대로 전달.
    user_prompt = f"아래 시나리오를 분석하여 이미지 생성 스타일 규칙을 JSON으로 생성하세요.\n\n---\n{fulltext}\n---"

    return call_structured(
        step="style_rules",
        system_prompt=system_prompt,
        user_prompt=user_prompt,
        response_schema=STYLE_RULES_SCHEMA,
        project_config=project_llm_config,
        schema_name="style_rules",
        max_tokens=4000,
    )
