"""
Camera Library for Cinematic Video Prompts.

Contains:
- 15+ named camera movements with descriptions
- Emotion-to-camera mapping guide
- Muscle/tendon table for joint-by-joint action descriptions
- Video prompt template builder
"""

from __future__ import annotations

from typing import Dict, List, Optional


# ---------------------------------------------------------------------------
# Camera Movement Library
# ---------------------------------------------------------------------------

CAMERA_MOVEMENTS: Dict[str, Dict[str, str]] = {
    # Static movements
    "LOCKED_STATIC": {
        "name": "LOCKED STATIC",
        "description": "Camera completely fixed, character moves within frame",
        "use_for": "Crucial decisions, dramatic pauses, dialogue",
        "kling_instruction": "static camera, no movement, character moves in frame",
    },
    "SUBTLE_DRIFT": {
        "name": "SUBTLE DRIFT",
        "description": "Almost imperceptible micro-movement, creates life without distraction",
        "use_for": "Intimacy, vulnerability, quiet moments",
        "kling_instruction": "very subtle camera drift, almost imperceptible movement",
    },
    
    # Horizontal movements
    "SLOW_PAN_LEFT": {
        "name": "SLOW PAN LEFT",
        "description": "Slow horizontal rotation to the left, reveals environment",
        "use_for": "Environment reveal, following action, scene establishment",
        "kling_instruction": "slow pan left, horizontal camera rotation",
    },
    "SLOW_PAN_RIGHT": {
        "name": "SLOW PAN RIGHT",
        "description": "Slow horizontal rotation to the right, reveals environment",
        "use_for": "Environment reveal, following action, scene establishment",
        "kling_instruction": "slow pan right, horizontal camera rotation",
    },
    "WHIP_PAN": {
        "name": "WHIP PAN",
        "description": "Fast horizontal rotation with motion blur, creates urgency",
        "use_for": "Chaos, panic, sudden attention shift, action transitions",
        "kling_instruction": "fast whip pan with motion blur",
    },
    
    # Vertical movements
    "TILT_UP": {
        "name": "TILT UP",
        "description": "Vertical rotation upward, reveals height or power",
        "use_for": "Revealing scale, showing dominance, looking up at threat",
        "kling_instruction": "camera tilts up vertically",
    },
    "TILT_DOWN": {
        "name": "TILT DOWN",
        "description": "Vertical rotation downward, reveals ground or vulnerability",
        "use_for": "Showing defeat, revealing what's below, introspection",
        "kling_instruction": "camera tilts down vertically",
    },
    "CRANE_UP": {
        "name": "CRANE UP",
        "description": "Physical vertical movement upward, elevates perspective",
        "use_for": "Epic moments, victory, transcendence, wide reveal",
        "kling_instruction": "crane shot moving up, elevating camera position",
    },
    "CRANE_DOWN": {
        "name": "CRANE DOWN",
        "description": "Physical vertical movement downward, grounds perspective",
        "use_for": "Despair, defeat, coming down to earth, intimacy",
        "kling_instruction": "crane shot moving down, lowering camera position",
    },
    
    # Depth movements
    "DOLLY_IN": {
        "name": "DOLLY IN",
        "description": "Physical camera movement toward subject",
        "use_for": "Building tension, focusing attention, emotional connection",
        "kling_instruction": "dolly in, camera moves toward subject",
    },
    "DOLLY_OUT": {
        "name": "DOLLY OUT",
        "description": "Physical camera movement away from subject",
        "use_for": "Revealing context, isolation, ending scenes",
        "kling_instruction": "dolly out, camera moves away from subject",
    },
    "PUSH_IN": {
        "name": "PUSH IN",
        "description": "Dramatic dolly in for emotional peak moments",
        "use_for": "Realization, decision moment, emotional climax",
        "kling_instruction": "dramatic push in toward subject face",
    },
    "PULL_BACK_REVEAL": {
        "name": "PULL BACK REVEAL",
        "description": "Dolly out that reveals surprising context",
        "use_for": "Plot twist, shocking revelation, scale reveal",
        "kling_instruction": "pull back reveal, camera retreats to show context",
    },
    
    # Complex movements
    "ORBIT": {
        "name": "ORBIT",
        "description": "Camera circles around the subject",
        "use_for": "Contemplation, hero moment, 360 character view",
        "kling_instruction": "orbit shot, camera circles around subject",
    },
    "TRACKING_SHOT": {
        "name": "TRACKING SHOT",
        "description": "Camera moves laterally alongside subject",
        "use_for": "Following action, walking conversations, pursuit",
        "kling_instruction": "tracking shot, camera moves alongside subject",
    },
    "FOLLOW_SHOT": {
        "name": "FOLLOW SHOT",
        "description": "Camera follows subject from behind",
        "use_for": "Journey, pursuit, entering new space",
        "kling_instruction": "follow shot from behind subject",
    },
    "HANDHELD": {
        "name": "HANDHELD",
        "description": "Organic movement with slight tremor, documentary feel",
        "use_for": "Urgency, chaos, realism, pursuit sequences",
        "kling_instruction": "handheld camera with organic movement",
    },
    "STEADICAM_FLOAT": {
        "name": "STEADICAM FLOAT",
        "description": "Smooth fluid movement without tremor",
        "use_for": "Dreamlike sequences, smooth following, elegant movement",
        "kling_instruction": "steadicam smooth floating movement",
    },
    
    # Special movements
    "VERTIGO_EFFECT": {
        "name": "VERTIGO EFFECT",
        "description": "Dolly + zoom in opposite direction (Hitchcock effect)",
        "use_for": "Disorientation, realization, psychological impact",
        "kling_instruction": "vertigo effect, dolly and zoom in opposite directions",
    },
    "CRASH_ZOOM": {
        "name": "CRASH ZOOM",
        "description": "Rapid dramatic zoom into subject",
        "use_for": "Shock, sudden focus, dramatic emphasis",
        "kling_instruction": "crash zoom, rapid zoom into subject",
    },
    "OVERHEAD_STATIC": {
        "name": "OVERHEAD STATIC",
        "description": "Bird's eye view looking straight down",
        "use_for": "Death scenes, isolation, scale, plot twist",
        "kling_instruction": "overhead bird's eye view, looking straight down",
    },
    "OVERHEAD_SLOW_PULLBACK": {
        "name": "OVERHEAD SLOW PULLBACK",
        "description": "Bird's eye view slowly pulling back to reveal scale",
        "use_for": "Death scenes, endings, isolation reveal",
        "kling_instruction": "overhead view slowly pulling back",
    },
}


# ---------------------------------------------------------------------------
# Emotion to Camera Movement Mapping
# ---------------------------------------------------------------------------

EMOTION_CAMERA_MAP: Dict[str, List[str]] = {
    "tension_building": ["PUSH_IN", "SLOW_PAN_LEFT", "DOLLY_IN"],
    "revelation_shock": ["PULL_BACK_REVEAL", "CRASH_ZOOM", "WHIP_PAN"],
    "intimacy_vulnerability": ["SUBTLE_DRIFT", "PUSH_IN", "DOLLY_IN"],
    "power_dominance": ["TILT_UP", "CRANE_UP", "ORBIT"],
    "despair_defeat": ["CRANE_DOWN", "TILT_DOWN", "OVERHEAD_STATIC"],
    "pursuit_urgency": ["HANDHELD", "TRACKING_SHOT", "FOLLOW_SHOT"],
    "contemplation": ["ORBIT", "SUBTLE_DRIFT", "STEADICAM_FLOAT"],
    "chaos_panic": ["WHIP_PAN", "HANDHELD", "CRASH_ZOOM"],
    "epic_moment": ["CRANE_UP", "ORBIT", "PULL_BACK_REVEAL"],
    "crucial_decision": ["LOCKED_STATIC", "PUSH_IN", "SUBTLE_DRIFT"],
    "death_ending": ["OVERHEAD_STATIC", "OVERHEAD_SLOW_PULLBACK", "CRANE_DOWN"],
    "action_intense": ["TRACKING_SHOT", "HANDHELD", "WHIP_PAN"],
    "isolation_loneliness": ["PULL_BACK_REVEAL", "OVERHEAD_STATIC", "DOLLY_OUT"],
    "victory_relief": ["CRANE_UP", "ORBIT", "PULL_BACK_REVEAL"],
    "fear_alert": ["HANDHELD", "PUSH_IN", "WHIP_PAN"],
}


# ---------------------------------------------------------------------------
# Muscle/Tendon Table for Joint-by-Joint Actions
# ---------------------------------------------------------------------------

ACTION_ANATOMY: Dict[str, Dict[str, str]] = {
    "throwing": {
        "muscles": "Anterior deltoid fires first. Pectoralis major pulls arm across. Biceps contracts on backswing. Triceps explodes on release.",
        "timing": "0.0-0.3s wind-up, 0.3-0.5s release, 0.5-0.8s follow-through",
        "visible_structures": "deltoid, pectoralis major, biceps, triceps",
    },
    "running_sprint": {
        "muscles": "Quadriceps expanding and contracting in 0.4s cycles. Hamstrings in eccentric contraction on landing. Gastrocnemius pushing off.",
        "timing": "0.4s per stride cycle, alternating legs",
        "visible_structures": "quadriceps, hamstrings, gastrocnemius, hip flexors",
    },
    "gripping_holding": {
        "muscles": "Flexor digitorum profundus contracts — muscle fibers visibly shortening. Flexor tendon running through finger.",
        "timing": "0.2s to full grip, sustained hold",
        "visible_structures": "flexor digitorum, extensor tendons, intrinsic hand muscles",
    },
    "chewing_biting": {
        "muscles": "Masseter muscle contracting and relaxing in rapid cycles. Temporalis pulsing at temples. Pterygoid assisting lateral movement.",
        "timing": "0.3s per chew cycle",
        "visible_structures": "masseter, temporalis, pterygoid",
    },
    "squatting_kneeling": {
        "muscles": "Quadriceps in eccentric contraction controlling descent. Gluteus maximus activating for support. Patellar tendon under tension.",
        "timing": "1.0-1.5s descent, 0.5s hold, 1.0s ascent",
        "visible_structures": "quadriceps, gluteus maximus, patellar tendon",
    },
    "deep_breathing": {
        "muscles": "Diaphragm descending — dome flattening. Intercostal muscles between each rib tensioning and expanding.",
        "timing": "2.0s inhale, 0.5s hold, 2.0s exhale",
        "visible_structures": "diaphragm, intercostals, rib cage expansion",
    },
    "drinking_swallowing": {
        "muscles": "Esophagus — tube descending from neck through chest in pink-beige tone. Peristaltic contractions visible descending.",
        "timing": "0.5s per swallow, visible wave descending",
        "visible_structures": "esophagus, pharynx, peristaltic wave",
    },
    "pressing_gripping_object": {
        "muscles": "Intrinsic hand muscles in full contraction. Extensor tendons on dorsal side in relief. Metacarpals arching.",
        "timing": "0.3s to full pressure, sustained",
        "visible_structures": "intrinsic hand muscles, extensor tendons, metacarpals",
    },
    "walking": {
        "muscles": "Hip flexors initiating swing phase. Quadriceps extending knee. Gastrocnemius pushing off. Tibialis anterior controlling foot.",
        "timing": "0.6s per step, alternating",
        "visible_structures": "hip flexors, quadriceps, gastrocnemius, tibialis anterior",
    },
    "lifting_carrying": {
        "muscles": "Erector spinae stabilizing spine. Latissimus dorsi pulling. Biceps flexing. Trapezius supporting shoulders.",
        "timing": "1.0s lift, sustained carry",
        "visible_structures": "erector spinae, latissimus dorsi, biceps, trapezius",
    },
    "climbing": {
        "muscles": "Latissimus dorsi pulling body up. Biceps flexing. Forearm flexors gripping. Quadriceps pushing from legs.",
        "timing": "1.5s per pull-up motion",
        "visible_structures": "latissimus dorsi, biceps, forearm flexors, quadriceps",
    },
    "falling_collapsing": {
        "muscles": "All muscles releasing tension. Limbs following gravity. No active contraction — passive fall.",
        "timing": "0.5-1.0s fall duration",
        "visible_structures": "relaxed musculature, gravity-driven positioning",
    },
}


# ---------------------------------------------------------------------------
# Video Prompt Template Builder
# ---------------------------------------------------------------------------

def build_video_prompt(
    camera_move: str,
    character_action: str,
    sound_effects: List[str],
    sync_word: str = "",
    scene_number: int = 0,
) -> str:
    """Build a complete video prompt following the mandatory template.
    
    Args:
        camera_move: Named camera movement from CAMERA_MOVEMENTS
        character_action: Detailed joint-by-joint action description
        sound_effects: List of physical SFX (no music, no voice)
        sync_word: Exact word/phrase from script for audio sync
        scene_number: Scene number for reference
    
    Returns:
        Formatted video prompt string
    """
    # Get camera details
    cam = CAMERA_MOVEMENTS.get(camera_move.upper().replace(" ", "_"), {})
    cam_name = cam.get("name", camera_move)
    cam_instruction = cam.get("kling_instruction", camera_move.lower())
    
    # Build SFX string
    sfx_str = ", ".join(sound_effects) if sound_effects else "ambient silence"
    
    # Build the prompt
    prompt_parts = [
        f"[CAMERA: {cam_name}] {cam_instruction}.",
        f"[ACTION] {character_action}",
        f"[SFX] {sfx_str}. NO music. NO voice.",
    ]
    
    return " ".join(prompt_parts)


def get_camera_for_emotion(emotion: str) -> str:
    """Get recommended camera movement for an emotional context.
    
    Args:
        emotion: Emotional context key from EMOTION_CAMERA_MAP
    
    Returns:
        First recommended camera movement name
    """
    movements = EMOTION_CAMERA_MAP.get(emotion.lower().replace(" ", "_"), [])
    return movements[0] if movements else "SUBTLE_DRIFT"


def get_action_anatomy(action: str) -> Dict[str, str]:
    """Get muscle/tendon details for a specific action.
    
    Args:
        action: Action key from ACTION_ANATOMY
    
    Returns:
        Dictionary with muscles, timing, and visible_structures
    """
    # Try exact match first
    if action.lower().replace(" ", "_") in ACTION_ANATOMY:
        return ACTION_ANATOMY[action.lower().replace(" ", "_")]
    
    # Try partial match
    for key, value in ACTION_ANATOMY.items():
        if action.lower() in key or key in action.lower():
            return value
    
    # Default
    return {
        "muscles": "Relevant muscle groups activating for the action",
        "timing": "Action-appropriate timing",
        "visible_structures": "Active musculature",
    }


# ---------------------------------------------------------------------------
# Kling AI Configuration
# ---------------------------------------------------------------------------

KLING_CONFIG = {
    "model": "Kling 2.0",
    "mode": "Pro Mode",
    "duration_base": "5s",
    "duration_epic": "10s",
    "aspect_ratio_vertical": "9:16",
    "aspect_ratio_horizontal": "16:9",
    "cfg_scale_range": "0.5-0.7",
    "negative_prompt": (
        "music, singing, voice, narration, dialogue, cartoon, animation, "
        "blur, shaky, fast cut, glow, internal light"
    ),
}


# ---------------------------------------------------------------------------
# Golden Rules for Video Prompts
# ---------------------------------------------------------------------------

GOLDEN_RULES = [
    "Every scene has INTENTIONAL camera movement. No accidents. No defaults.",
    "Camera serves the emotion, not the other way around.",
    "Vary movements. Monotony kills narrative. Use the full library.",
    "Video prompt describes ONLY action and camera. The image already exists.",
    "NO MUSIC. NO MUSIC. NO MUSIC. Never.",
    "Character ALWAYS comes from the image. Video CONTINUES from it.",
    "Describe action joint-by-joint. 'The skeleton runs' is not animation.",
    "Visible muscles and tendons — real anatomy. No imaginary glow.",
    "Each scene starts exactly where the previous ended. Continuity is everything.",
    "The sync word is the beat. Camera must ARRIVE at it.",
    "Close-ups reveal. Wide shots isolate. Use both.",
    "Silence between sound effects is also a sound effect.",
    "Read the complete sequence before touching a single prompt.",
    "Consecutive scenes MUST CONTRAST in camera type.",
    "Photorealistic always. Clinical always. Cinema always.",
    "Don't describe environment. Don't describe clothing. Don't describe what the image already shows.",
    "Shallow actions destroy animation. Every micro-movement counts.",
]
