#!/usr/bin/env python3
"""
Microdrama Styles Library for Satirical News Videos

Provides:
- VISUAL_STYLES - Styles adapted for satirical news content
- VIDEO_KINDS - News/satire specific formats
- Selection functions for matching style to content
"""

import random
from typing import Dict, List, Optional, Tuple


# === VISUAL STYLES FOR SATIRICAL NEWS ===

VISUAL_STYLES = {
    # === NEWS/DOCUMENTARY STYLES ===
    "news_broadcast": {
        "name": "News Broadcast",
        "weight": 15,
        "prompt_hint": "Professional TV news studio aesthetic, well-lit, clean background, news anchor presentation",
        "nanobanana_style": "Cinematic / Film Still",
        "good_for": ["official_statements", "breaking_news", "press_conferences"]
    },
    "documentary": {
        "name": "Documentary",
        "weight": 12,
        "prompt_hint": "BBC/Discovery documentary style, observational, natural lighting, authentic moments",
        "nanobanana_style": "Cinematic / Film Still",
        "good_for": ["historical", "investigations", "deep_dives"]
    },
    "archive_footage": {
        "name": "Archive Footage",
        "weight": 10,
        "prompt_hint": "Old newsreel aesthetic, grainy texture, vintage camera quality, historical footage feel",
        "nanobanana_style": "Retro / Vintage",
        "good_for": ["historical", "flashbacks", "discovered_documents"]
    },
    "mockumentary": {
        "name": "Mockumentary",
        "weight": 10,
        "prompt_hint": "The Office style mockumentary, confessional interviews, knowing glances at camera",
        "nanobanana_style": "Cinematic / Film Still",
        "good_for": ["absurd_quotes", "workplace_satire"]
    },

    # === RUSSIAN/SOVIET STYLES ===
    "soviet_newsreel": {
        "name": "Soviet Newsreel",
        "weight": 8,
        "prompt_hint": "Soviet propaganda newsreel style, heroic angles, triumphant lighting, optimistic workers",
        "nanobanana_style": "Retro / Vintage",
        "good_for": ["russian_politics", "nostalgic", "propaganda_parody"]
    },
    "russian_tv": {
        "name": "Russian TV",
        "weight": 10,
        "prompt_hint": "Modern Russian television aesthetic, talk show lighting, dramatic presenter style",
        "nanobanana_style": "Cinematic / Film Still",
        "good_for": ["political_satire", "talk_shows", "debates"]
    },
    "soviet_cartoon": {
        "name": "Soviet Cartoon",
        "weight": 8,
        "prompt_hint": "Classic Soviet animation style (Soyuzmultfilm), soft watercolors, gentle characters, nostalgic charm",
        "nanobanana_style": "Illustration",
        "good_for": ["cheburashka", "nu_pogodi", "soviet_characters"]
    },
    "soviet_nature_doc": {
        "name": "Soviet Nature Documentary",
        "weight": 10,
        "prompt_hint": "Nikolai Drozdov 'В мире животных' style, warm 1980s Soviet TV aesthetic, earnest scientific presentation, zoo enclosures, sepia-warm color grade, gentle narrator energy, slightly faded film look, educational but cozy",
        "nanobanana_style": "Retro / Vintage",
        "good_for": ["animals", "zoos", "scientific_absurd", "deadpan_comedy", "import_substitution"]
    },

    # === DRAMATIC/CINEMATIC STYLES ===
    "thriller": {
        "name": "Thriller",
        "weight": 7,
        "prompt_hint": "Political thriller aesthetic, suspenseful lighting, shadowy figures, tension",
        "nanobanana_style": "Cinematic / Film Still",
        "good_for": ["espionage", "conspiracy", "secret_meetings"]
    },
    "noir": {
        "name": "Film Noir",
        "weight": 6,
        "prompt_hint": "High contrast black and white, dramatic shadows, mysterious atmosphere, detective film",
        "nanobanana_style": "Cinematic / Film Still",
        "good_for": ["investigations", "mysterious", "criminal"]
    },
    "cinematic": {
        "name": "Cinematic",
        "weight": 12,
        "prompt_hint": "Professional film quality, natural outdoor lighting, realistic atmosphere, movie scene aesthetic, no studio look",
        "nanobanana_style": "Cinematic / Film Still",
        "good_for": ["outdoor_scenes", "realistic", "dark_comedy", "slice_of_life"]
    },
    "melodrama": {
        "name": "Melodrama",
        "weight": 8,
        "prompt_hint": "Over-the-top emotional scenes, dramatic reactions, telenovela intensity, exaggerated expressions",
        "nanobanana_style": "Cinematic / Film Still",
        "good_for": ["emotional_reactions", "victim_stories", "personal_drama"]
    },

    # === COMEDIC STYLES ===
    "sitcom": {
        "name": "Sitcom",
        "weight": 7,
        "prompt_hint": "TV sitcom aesthetic, bright lighting, reaction shots, comedic timing setup",
        "nanobanana_style": "Cinematic / Film Still",
        "good_for": ["absurd_situations", "workplace_humor", "domestic"]
    },
    "meme_style": {
        "name": "Meme Style",
        "weight": 8,
        "prompt_hint": "Internet meme aesthetic, reaction face moments, viral video energy, shareable visuals",
        "nanobanana_style": "Cinematic / Film Still",
        "good_for": ["reactions", "viral_moments", "internet_culture"]
    },
    "cartoon_news": {
        "name": "Cartoon News",
        "weight": 10,
        "prompt_hint": "Animated news parody style, bold colors, exaggerated expressions, cartoon satire",
        "nanobanana_style": "Illustration",
        "good_for": ["absurd_news", "animated_characters", "parody"]
    },

    # === ARTISTIC STYLES ===
    "propaganda_poster": {
        "name": "Propaganda Poster",
        "weight": 5,
        "prompt_hint": "Bold propaganda poster aesthetic, heroic poses, dramatic text, call to action style",
        "nanobanana_style": "Illustration",
        "good_for": ["political_statements", "heroic_moments", "satire"]
    },
    "expressionist": {
        "name": "Expressionist",
        "weight": 4,
        "prompt_hint": "German expressionism style, distorted angles, exaggerated shadows, emotional intensity",
        "nanobanana_style": "Cinematic / Film Still",
        "good_for": ["psychological", "dark_themes", "intense_moments"]
    },
    "pop_art_news": {
        "name": "Pop Art News",
        "weight": 5,
        "prompt_hint": "Warhol-inspired news satire, bold primary colors, Ben-Day dots, celebrity culture critique",
        "nanobanana_style": "Illustration",
        "good_for": ["celebrity", "media_satire", "consumer_culture"]
    },

    # === SPECIAL FORMATS ===
    "home_video": {
        "name": "Home Video",
        "weight": 6,
        "prompt_hint": "Amateur home video aesthetic, shaky cam, natural lighting, authentic candid feel",
        "nanobanana_style": "Cinematic / Film Still",
        "good_for": ["personal_stories", "caught_on_camera", "intimate"]
    },
    "security_cam": {
        "name": "Security Camera",
        "weight": 4,
        "prompt_hint": "CCTV surveillance footage style, grainy, timestamp overlay, fixed angle",
        "nanobanana_style": "Cinematic / Film Still",
        "good_for": ["evidence", "caught_in_act", "surveillance"]
    },
    "courtroom": {
        "name": "Courtroom Drama",
        "weight": 5,
        "prompt_hint": "Courtroom trial aesthetic, formal setting, dramatic testimony moments, legal drama",
        "nanobanana_style": "Cinematic / Film Still",
        "good_for": ["trials", "accusations", "legal_satire"]
    }
}


# === VIDEO KINDS FOR SATIRICAL NEWS ===

VIDEO_KINDS = {
    # === NEWS FORMATS ===
    "breaking_news": {
        "name": "Breaking News",
        "weight": 15,
        "prompt_hint": "URGENT breaking news energy, dramatic reveal, shocking announcement",
        "energy": "urgent",
        "structure": "hook_heavy"
    },
    "investigation": {
        "name": "Investigation",
        "weight": 10,
        "prompt_hint": "Investigative journalism style, uncovering truth, dramatic discoveries",
        "energy": "building",
        "structure": "mystery_reveal"
    },
    "press_conference": {
        "name": "Press Conference",
        "weight": 8,
        "prompt_hint": "Official statement parody, podium drama, journalist reactions",
        "energy": "formal_then_chaos",
        "structure": "statement_reaction"
    },
    "interview": {
        "name": "Interview",
        "weight": 8,
        "prompt_hint": "One-on-one interview style, revelations, emotional moments",
        "energy": "intimate",
        "structure": "conversation"
    },

    # === REACTION/PERSONAL ===
    "victim_story": {
        "name": "Victim's Story",
        "weight": 10,
        "prompt_hint": "Personal tragedy storytelling, emotional journey from shock to acceptance",
        "energy": "emotional",
        "structure": "emotional_arc"
    },
    "witness_account": {
        "name": "Witness Account",
        "weight": 7,
        "prompt_hint": "Eyewitness testimony style, I was there energy, dramatic retelling",
        "energy": "recounting",
        "structure": "flashback"
    },
    "reaction_video": {
        "name": "Reaction Video",
        "weight": 9,
        "prompt_hint": "Internet reaction video energy, real-time shock and disbelief",
        "energy": "dynamic",
        "structure": "discovery_reaction"
    },

    # === COMEDY/SATIRE ===
    "absurdist": {
        "name": "Absurdist",
        "weight": 12,
        "prompt_hint": "Escalating absurdity, deadpan delivery of ridiculous content, surreal logic",
        "energy": "building_absurdity",
        "structure": "escalation"
    },
    "parody": {
        "name": "Parody",
        "weight": 10,
        "prompt_hint": "Genre parody energy, exaggerated tropes, comedic subversion",
        "energy": "playful",
        "structure": "trope_subversion"
    },
    "satire_commentary": {
        "name": "Satire Commentary",
        "weight": 8,
        "prompt_hint": "Satirical news commentary, ironic observations, social critique",
        "energy": "wry",
        "structure": "observation_punchline"
    },

    # === DRAMATIC ===
    "conspiracy_reveal": {
        "name": "Conspiracy Reveal",
        "weight": 7,
        "prompt_hint": "Conspiracy theory unraveling, connecting dots, dramatic revelations",
        "energy": "paranoid",
        "structure": "buildup_reveal"
    },
    "scandal": {
        "name": "Scandal",
        "weight": 8,
        "prompt_hint": "Breaking scandal energy, shocking revelations, public outrage",
        "energy": "explosive",
        "structure": "expose"
    },
    "diplomatic_incident": {
        "name": "Diplomatic Incident",
        "weight": 6,
        "prompt_hint": "International incident drama, formal outrage, diplomatic posturing",
        "energy": "tense",
        "structure": "escalation_resolution"
    },

    # === NOSTALGIA ===
    "nostalgic": {
        "name": "Nostalgic",
        "weight": 7,
        "prompt_hint": "Warm nostalgia, fond memories, bittersweet reflection",
        "energy": "warm",
        "structure": "memory_present"
    },
    "historical_parallel": {
        "name": "Historical Parallel",
        "weight": 5,
        "prompt_hint": "Drawing parallels to history, those who forget are doomed energy",
        "energy": "ominous",
        "structure": "past_present_mirror"
    }
}


# === STYLE SELECTION FUNCTIONS ===

def select_style_for_content(
    article_themes: List[str],
    characters: Dict,
    storyteller_type: str
) -> Tuple[str, str]:
    """
    Select visual style and video kind based on content analysis.

    Args:
        article_themes: List of themes from article analysis (e.g., ["political", "absurd", "nostalgic"])
        characters: Character dict from script (to check for cartoons, real people)
        storyteller_type: Type of storyteller (victim, news_anchor, etc.)

    Returns:
        Tuple of (visual_style_key, video_kind_key)
    """
    # Check for cartoon characters
    has_cartoon = any(
        char.get("is_cartoon", False)
        for char in characters.values()
    )

    # Check for Soviet/Russian nostalgia themes
    soviet_themes = ["cheburashka", "soviet", "nostalgic", "cartoon_character"]
    has_soviet_nostalgia = any(theme in article_themes for theme in soviet_themes)

    # Check for espionage/intelligence themes
    spy_themes = ["mossad", "spy", "intelligence", "secret_service", "espionage"]
    has_spy_theme = any(theme in article_themes for theme in spy_themes)

    # Check for political themes
    political_themes = ["political", "government", "diplomatic", "official"]
    has_political = any(theme in article_themes for theme in political_themes)

    # Select visual style based on content
    if has_cartoon and has_soviet_nostalgia:
        # Soviet cartoon characters - use cartoon or melodrama style
        style_candidates = ["soviet_cartoon", "melodrama", "cartoon_news", "nostalgic"]
    elif has_spy_theme:
        # Spy/intelligence stories
        style_candidates = ["thriller", "noir", "documentary"]
    elif has_political:
        # Political satire
        style_candidates = ["news_broadcast", "russian_tv", "mockumentary"]
    elif storyteller_type == "victim":
        # Victim POV stories
        style_candidates = ["melodrama", "home_video", "documentary"]
    else:
        # Default to news/documentary styles
        style_candidates = ["news_broadcast", "documentary", "mockumentary"]

    # Weight selection toward first candidates
    weights = [10 - i*2 for i in range(len(style_candidates))]
    visual_style = random.choices(style_candidates, weights=weights, k=1)[0]

    # Select video kind based on storyteller and themes
    if storyteller_type == "victim":
        kind_candidates = ["victim_story", "reaction_video", "witness_account"]
    elif has_spy_theme:
        kind_candidates = ["conspiracy_reveal", "scandal", "investigation"]
    elif "absurd" in article_themes:
        kind_candidates = ["absurdist", "parody", "reaction_video"]
    elif has_soviet_nostalgia:
        kind_candidates = ["nostalgic", "victim_story", "absurdist"]
    else:
        kind_candidates = ["breaking_news", "investigation", "satire_commentary"]

    weights = [10 - i*2 for i in range(len(kind_candidates))]
    video_kind = random.choices(kind_candidates, weights=weights, k=1)[0]

    return (visual_style, video_kind)


def get_style_config(style_key: str) -> Dict:
    """Get configuration for a visual style."""
    return VISUAL_STYLES.get(style_key, VISUAL_STYLES["news_broadcast"])


def get_kind_config(kind_key: str) -> Dict:
    """Get configuration for a video kind."""
    return VIDEO_KINDS.get(kind_key, VIDEO_KINDS["breaking_news"])


def get_style_prompt_context(style_key: str, kind_key: str) -> str:
    """
    Build creative direction context for Claude prompt.

    Returns formatted text describing visual style and video kind.
    """
    style = get_style_config(style_key)
    kind = get_kind_config(kind_key)

    return f"""## Creative Direction

**Visual Style**: {style['name']}
{style['prompt_hint']}
NanoBanana style hint: {style.get('nanobanana_style', 'Cinematic / Film Still')}

**Video Kind**: {kind['name']}
{kind['prompt_hint']}
Energy level: {kind['energy']}
Story structure: {kind.get('structure', 'standard')}

Apply this style to ALL frame descriptions:
- Visual atmosphere should match the style (lighting, color grading, composition)
- Character expressions and poses should match the energy level
- Scene transitions should follow the story structure
"""


def get_frame_style_hints(style_key: str) -> Dict[str, str]:
    """
    Get style-specific hints for frame generation.

    Returns dict with hints for different aspects of the frame.
    """
    style = get_style_config(style_key)

    # Default hints
    hints = {
        "lighting": "professional studio lighting",
        "color_grade": "natural colors",
        "atmosphere": "neutral",
        "camera": "eye level, medium shot",
        "nanobanana_style": style.get("nanobanana_style", "Cinematic / Film Still")
    }

    # Style-specific overrides
    style_hints = {
        "news_broadcast": {
            "lighting": "bright TV studio lighting, soft key light",
            "color_grade": "clean, slightly warm",
            "atmosphere": "professional, formal",
            "camera": "eye level, medium close-up"
        },
        "documentary": {
            "lighting": "natural lighting, observational",
            "color_grade": "slightly desaturated, realistic",
            "atmosphere": "authentic, unposed",
            "camera": "handheld feel, varied angles"
        },
        "archive_footage": {
            "lighting": "harsh, uneven vintage lighting",
            "color_grade": "sepia or faded colors, grain",
            "atmosphere": "historical, aged",
            "camera": "static, period-appropriate framing"
        },
        "soviet_cartoon": {
            "lighting": "soft, even illustration lighting",
            "color_grade": "pastel watercolors, gentle tones",
            "atmosphere": "nostalgic, warm, innocent",
            "camera": "classic animation framing"
        },
        "melodrama": {
            "lighting": "dramatic, high contrast",
            "color_grade": "saturated, emotional",
            "atmosphere": "intense emotions, theatrical",
            "camera": "close-ups on reactions, dramatic angles"
        },
        "thriller": {
            "lighting": "low key, shadows, tension",
            "color_grade": "cold, desaturated blues",
            "atmosphere": "suspenseful, paranoid",
            "camera": "dutch angles, tight framing"
        },
        "noir": {
            "lighting": "high contrast, dramatic shadows",
            "color_grade": "black and white or high contrast",
            "atmosphere": "mysterious, shadowy",
            "camera": "low angles, dramatic framing"
        },
        "cinematic": {
            "lighting": "natural outdoor lighting, overcast sky, soft diffused light",
            "color_grade": "realistic colors, slightly desaturated, moody",
            "atmosphere": "realistic outdoor environment, authentic location, no studio",
            "camera": "professional film framing, varied shots"
        },
        "home_video": {
            "lighting": "natural, available light",
            "color_grade": "slightly overexposed, amateur",
            "atmosphere": "candid, authentic",
            "camera": "handheld, imperfect framing"
        },
        "meme_style": {
            "lighting": "bright, clear",
            "color_grade": "vivid, internet aesthetic",
            "atmosphere": "reaction-worthy, shareable",
            "camera": "reaction shot framing"
        },
        "cartoon_news": {
            "lighting": "bright, cartoon lighting",
            "color_grade": "bold, saturated cartoon colors",
            "atmosphere": "animated, exaggerated",
            "camera": "dynamic cartoon angles"
        },
        "russian_tv": {
            "lighting": "talk show lighting, dramatic",
            "color_grade": "saturated, TV aesthetic",
            "atmosphere": "formal but theatrical",
            "camera": "medium shots, presenter framing"
        },
        "soviet_nature_doc": {
            "lighting": "warm natural lighting, 1980s TV quality",
            "color_grade": "sepia-warm, slightly faded, film grain, nostalgic tones",
            "atmosphere": "earnest scientific, educational but cozy, deadpan serious",
            "camera": "observational nature documentary framing, zoo enclosures, outdoor shots"
        }
    }

    if style_key in style_hints:
        hints.update(style_hints[style_key])

    return hints


def format_style_for_display(style_key: str, kind_key: str) -> str:
    """Format style/kind for display in logs or captions."""
    style = get_style_config(style_key)
    kind = get_kind_config(kind_key)
    return f"{style['name']} | {kind['name']}"


# List available styles for reference
def list_styles() -> str:
    """List all available visual styles."""
    lines = ["## Available Visual Styles\n"]
    for key, config in VISUAL_STYLES.items():
        lines.append(f"- **{key}**: {config['name']} - {config['prompt_hint'][:60]}...")
    return "\n".join(lines)


def list_kinds() -> str:
    """List all available video kinds."""
    lines = ["## Available Video Kinds\n"]
    for key, config in VIDEO_KINDS.items():
        lines.append(f"- **{key}**: {config['name']} - {config['prompt_hint'][:50]}... (energy: {config['energy']})")
    return "\n".join(lines)


if __name__ == "__main__":
    print("=== Microdrama Styles Library ===")
    print(f"Total visual styles: {len(VISUAL_STYLES)}")
    print(f"Total video kinds: {len(VIDEO_KINDS)}")
    print()

    print("=== Test Selection ===")
    # Test with Cheburashka/Mossad themes
    themes = ["political", "espionage", "cheburashka", "absurd"]
    characters = {
        "storyteller": {"is_cartoon": True},
        "mossad_chief": {"is_real_person": False}
    }
    style, kind = select_style_for_content(themes, characters, "victim")
    print(f"Themes: {themes}")
    print(f"Selected: {format_style_for_display(style, kind)}")
    print()

    print("=== Style Hints ===")
    hints = get_frame_style_hints(style)
    for key, value in hints.items():
        print(f"  {key}: {value}")
