#!/usr/bin/env python3
"""
Creative Styles Library for Video Generation Pipeline

Provides:
- VISUAL_STYLES - 20 graphical/artistic rendering styles
- VIDEO_KINDS - 18 mood/format/energy types
- Selection functions for random weighted selection
- Claude-based intelligent style selection from feedback
"""

import json
import random
import subprocess
import os
from typing import Dict, List, Optional, Tuple


# === VISUAL STYLES LIBRARY (20 styles) ===
# photorealistic=True means style is suitable for marketplace product shots
# photorealistic=False means artistic/creative style (use after first tries or on request)

VISUAL_STYLES = {
    # === PHOTOREALISTIC STYLES (marketplace-safe, use first) ===
    "cinematic": {
        "name": "Cinematic",
        "weight": 20,
        "photorealistic": True,
        "prompt_hint": "Cinematic film look, movie-quality lighting, professional cinematography",
        "nanobanana_style": "Cinematic / Film Still"
    },
    "noir": {
        "name": "Film Noir",
        "weight": 6,
        "photorealistic": True,
        "prompt_hint": "High contrast black and white, dramatic shadows, mysterious detective film atmosphere",
        "nanobanana_style": "Cinematic / Film Still"
    },
    "western": {
        "name": "Western",
        "weight": 4,
        "photorealistic": True,
        "prompt_hint": "Wild West aesthetic, dusty desert, sepia tones, cowboy showdown, saloon doors",
        "nanobanana_style": "Cinematic / Film Still"
    },
    "horror": {
        "name": "Horror",
        "weight": 3,
        "photorealistic": True,
        "prompt_hint": "Horror movie aesthetic, dramatic shadows, ominous atmosphere, suspenseful lighting",
        "nanobanana_style": "Cinematic / Film Still"
    },
    "retro_50s": {
        "name": "Retro 50s",
        "weight": 7,
        "photorealistic": True,
        "prompt_hint": "1950s advertising aesthetic, pastel colors, optimistic mood, vintage Americana, housewife smile",
        "nanobanana_style": "Retro / Vintage"
    },
    "art_deco": {
        "name": "Art Deco",
        "weight": 5,
        "photorealistic": True,
        "prompt_hint": "1920s Art Deco elegance, Great Gatsby style, geometric patterns, gold and black, champagne glamour, ornate frames, jazz age luxury",
        "nanobanana_style": "Cinematic / Film Still"
    },
    "soviet_retro": {
        "name": "Soviet Retro",
        "weight": 6,
        "photorealistic": True,
        "prompt_hint": "Soviet 1960s-80s optimistic aesthetic, warm colors, cheerful workers, socialist realism poster style but cinematic, positive mood, communal joy",
        "nanobanana_style": "Retro / Vintage"
    },
    "russian_fairy_tale": {
        "name": "Russian Fairy Tale",
        "weight": 5,
        "photorealistic": True,
        "prompt_hint": "Russian folk tale aesthetic (Palekh, Khokhloma style influence), magical winter forest, ornate wooden architecture, Firebird colors, enchanted atmosphere, Ivan Bilibin illustration style but cinematic",
        "nanobanana_style": "Illustration"
    },
    "russian_silver_age": {
        "name": "Russian Silver Age",
        "weight": 4,
        "photorealistic": True,
        "prompt_hint": "Early 20th century Russian aesthetic, pre-revolution elegance, Art Nouveau influence, Mir Iskusstva style, poetic atmosphere, Serov portraits mood",
        "nanobanana_style": "Cinematic / Film Still"
    },
    "russian_aristocracy": {
        "name": "Russian Aristocracy",
        "weight": 4,
        "photorealistic": True,
        "prompt_hint": "19th century Russian nobility, Leo Tolstoy era, grand ballrooms, winter troika rides, elegant estates, Anna Karenina aesthetic, candlelit chandeliers, snow and fur",
        "nanobanana_style": "Cinematic / Film Still"
    },
    "soviet_constructivism": {
        "name": "Soviet Constructivism",
        "weight": 5,
        "photorealistic": True,
        "prompt_hint": "1920s-30s Soviet avant-garde, Rodchenko angles, bold red and black, geometric composition, heroic workers, Komsomol energy, positive industrial aesthetic, Stakhanovite spirit",
        "nanobanana_style": "Retro / Vintage"
    },
    "stalinist_empire": {
        "name": "Stalinist Empire",
        "weight": 4,
        "photorealistic": True,
        "prompt_hint": "1940s-50s Soviet grandeur, monumental architecture, triumphant mood, VDNH aesthetic, Moscow metro elegance, socialist classicism, abundant harvest imagery, optimistic future",
        "nanobanana_style": "Cinematic / Film Still"
    },
    "fashion_runway": {
        "name": "Fashion Runway",
        "weight": 6,
        "photorealistic": True,
        "prompt_hint": "High fashion runway show, dramatic catwalk lighting, model poses, fashion week glamour, designer presentation, editorial photography style, Vogue aesthetic",
        "nanobanana_style": "Cinematic / Film Still"
    },
    "disco": {
        "name": "Disco",
        "weight": 5,
        "photorealistic": True,
        "prompt_hint": "1970s-80s disco era, mirror ball reflections, colorful dance floor lights, Saturday Night Fever energy, glamorous nightclub, sparkling outfits, dance moves",
        "nanobanana_style": "Cinematic / Film Still"
    },
    "rock_concert": {
        "name": "Rock Concert",
        "weight": 5,
        "photorealistic": True,
        "prompt_hint": "Epic rock concert atmosphere, dramatic stage lighting, smoke and lasers, guitar hero moment, crowd energy, stadium lights, rock star pose",
        "nanobanana_style": "Cinematic / Film Still"
    },
    "punk": {
        "name": "Punk",
        "weight": 4,
        "photorealistic": True,
        "prompt_hint": "Punk rock aesthetic, DIY attitude, safety pins and patches, gritty urban, rebellious energy, garage band vibe, raw and authentic",
        "nanobanana_style": "Cinematic / Film Still"
    },
    "hip_hop": {
        "name": "Hip Hop",
        "weight": 5,
        "photorealistic": True,
        "prompt_hint": "Hip hop culture aesthetic, street style, urban backdrop, gold chains, boombox era or modern trap, confident swagger, music video energy",
        "nanobanana_style": "Cinematic / Film Still"
    },
    "grunge": {
        "name": "Grunge",
        "weight": 4,
        "photorealistic": True,
        "prompt_hint": "90s Seattle grunge aesthetic, flannel shirts, moody lighting, alternative rock atmosphere, garage vibes, authentic raw emotion",
        "nanobanana_style": "Cinematic / Film Still"
    },
    "glam_rock": {
        "name": "Glam Rock",
        "weight": 4,
        "photorealistic": True,
        "prompt_hint": "70s glam rock aesthetic, glitter and sequins, androgynous style, theatrical makeup, David Bowie energy, dramatic poses, flashy costumes",
        "nanobanana_style": "Cinematic / Film Still"
    },
    "rave": {
        "name": "Rave",
        "weight": 4,
        "photorealistic": True,
        "prompt_hint": "90s rave culture, UV lights, neon colors, warehouse party, electronic music energy, glow sticks, euphoric dance, PLUR vibes",
        "nanobanana_style": "Cinematic / Film Still"
    },

    # === ARTISTIC/CREATIVE STYLES (use on retries or user request) ===
    "cartoon": {
        "name": "Cartoon",
        "weight": 12,
        "photorealistic": False,
        "prompt_hint": "Bold cartoon style, vibrant colors, exaggerated proportions, animated feel",
        "nanobanana_style": "Illustration"
    },
    "anime": {
        "name": "Anime",
        "weight": 10,
        "photorealistic": False,
        "prompt_hint": "Japanese anime style, expressive eyes, dynamic poses, cel-shaded look",
        "nanobanana_style": "Anime / Manga"
    },
    "comic_book": {
        "name": "Comic Book",
        "weight": 8,
        "photorealistic": False,
        "prompt_hint": "Bold comic book style, ink outlines, halftone dots, POW/BAM effects, superhero aesthetic",
        "nanobanana_style": "Comic / Graphic Novel"
    },
    "3d_pixar": {
        "name": "3D Pixar Style",
        "weight": 8,
        "photorealistic": False,
        "prompt_hint": "Pixar/Disney 3D animation style, smooth surfaces, expressive characters, family-friendly",
        "nanobanana_style": "3D Render"
    },
    "cyberpunk": {
        "name": "Cyberpunk",
        "weight": 6,
        "photorealistic": False,
        "prompt_hint": "Neon-lit cyberpunk aesthetic, futuristic city, rain-slicked streets, holographic elements",
        "nanobanana_style": "Cyberpunk / Sci-Fi"
    },
    "vaporwave": {
        "name": "Vaporwave",
        "weight": 5,
        "photorealistic": False,
        "prompt_hint": "Vaporwave/synthwave aesthetic, pink and cyan neon, retro-futuristic, 80s nostalgia, grid lines",
        "nanobanana_style": "Cyberpunk / Sci-Fi"
    },
    "steampunk": {
        "name": "Steampunk",
        "weight": 5,
        "photorealistic": False,
        "prompt_hint": "Victorian steampunk aesthetic, brass gears, copper pipes, steam-powered, goggles and clockwork",
        "nanobanana_style": "Retro / Vintage"
    },
    "pop_art": {
        "name": "Pop Art",
        "weight": 5,
        "photorealistic": False,
        "prompt_hint": "Warhol-style pop art, bold primary colors, Ben-Day dots, repetition, commercial art aesthetic",
        "nanobanana_style": "Illustration"
    },
    "ukiyo_e": {
        "name": "Ukiyo-e",
        "weight": 3,
        "photorealistic": False,
        "prompt_hint": "Japanese woodblock print style, flat colors, bold outlines, traditional Edo period aesthetic",
        "nanobanana_style": "Ink / Chinese Style"
    },
    "watercolor": {
        "name": "Watercolor",
        "weight": 5,
        "photorealistic": False,
        "prompt_hint": "Soft watercolor painting, flowing colors, dreamy wet edges, artistic texture",
        "nanobanana_style": "Watercolor"
    },
    "chibi": {
        "name": "Chibi/Kawaii",
        "weight": 4,
        "photorealistic": False,
        "prompt_hint": "Cute chibi style, oversized heads, tiny bodies, kawaii expressions, adorable",
        "nanobanana_style": "Chibi / Q-Style"
    },
    "gothic": {
        "name": "Gothic",
        "weight": 3,
        "photorealistic": False,
        "prompt_hint": "Gothic aesthetic, dark romance, cathedral shadows, Victorian mourning, ravens and roses",
        "nanobanana_style": "Illustration"
    },
    "surreal": {
        "name": "Surreal",
        "weight": 4,
        "photorealistic": False,
        "prompt_hint": "Surrealist art style, Dali-esque dreamscape, impossible physics, melting reality",
        "nanobanana_style": "Oil Painting"
    },
    "pixel_art": {
        "name": "Pixel Art",
        "weight": 3,
        "photorealistic": False,
        "prompt_hint": "8-bit pixel art style, retro gaming aesthetic, chunky pixels, limited palette",
        "nanobanana_style": "Pixel Art"
    }
}


# === VIDEO KINDS LIBRARY (18 kinds) ===

VIDEO_KINDS = {
    # === HIGH WEIGHT (common) ===
    "standard": {
        "name": "Standard Promo",
        "weight": 15,
        "prompt_hint": "Professional product demonstration, lifestyle integration",
        "energy": "moderate",
        "archetype_bias": None
    },
    "meme": {
        "name": "Meme / Viral",
        "weight": 12,
        "prompt_hint": "Internet meme energy, unexpected twist, shareable moment, comedic timing, freeze frame",
        "energy": "high",
        "archetype_bias": "epic_hero"
    },
    "dance": {
        "name": "Dance / Music Video",
        "weight": 10,
        "prompt_hint": "Rhythmic movement, dancing, energetic vibes, music video aesthetic, celebration",
        "energy": "very_high",
        "archetype_bias": None
    },

    # === MEDIUM WEIGHT (periodic variety) ===
    "superhero": {
        "name": "Superhero",
        "weight": 8,
        "prompt_hint": "Superhero movie moment, dramatic hero pose, cape flowing, saving the day, epic entrance",
        "energy": "epic",
        "archetype_bias": "epic_hero"
    },
    "action_movie": {
        "name": "Action Movie",
        "weight": 7,
        "prompt_hint": "Action movie sequence, dramatic slow-motion, explosion energy, intense focus, hero moment",
        "energy": "intense",
        "archetype_bias": "epic_hero"
    },
    "romance": {
        "name": "Romance",
        "weight": 6,
        "prompt_hint": "Romantic movie moment, soft focus, warm glow, tender emotion, love story",
        "energy": "tender",
        "archetype_bias": "product_lifestyle"
    },
    "fairy_tale": {
        "name": "Fairy Tale",
        "weight": 8,
        "prompt_hint": "Once upon a time mood, magical transformation, enchanted sparkles, storybook ending",
        "energy": "dreamy",
        "archetype_bias": "before_after"
    },
    "thriller": {
        "name": "Thriller / Suspense",
        "weight": 5,
        "prompt_hint": "Thriller movie tension, suspenseful reveal, dramatic pause, edge of seat moment",
        "energy": "tense",
        "archetype_bias": "discovery"
    },
    "circus": {
        "name": "Circus / Magic Show",
        "weight": 7,
        "prompt_hint": "Ta-da reveal, magician flourish, showmanship, dramatic presentation, spotlight moment",
        "energy": "theatrical",
        "archetype_bias": "discovery"
    },
    "infomercial": {
        "name": "Infomercial",
        "weight": 6,
        "prompt_hint": "Over-the-top infomercial style, BUT WAIT THERE'S MORE, amazed reactions, before/after drama",
        "energy": "enthusiastic",
        "archetype_bias": "problem_solution"
    },
    "unboxing": {
        "name": "Unboxing",
        "weight": 7,
        "prompt_hint": "Satisfying unboxing moment, package reveal, first touch excitement, collector joy",
        "energy": "anticipation",
        "archetype_bias": "discovery"
    },

    # === LOWER WEIGHT (special occasions) ===
    "documentary": {
        "name": "Documentary",
        "weight": 5,
        "prompt_hint": "Observational documentary style, authentic moments, slice of life, real and unposed",
        "energy": "calm",
        "archetype_bias": "ritual"
    },
    "standup": {
        "name": "Comedy Sketch",
        "weight": 6,
        "prompt_hint": "Sitcom timing, comedic reaction shots, exaggerated expressions, punchline moment",
        "energy": "playful",
        "archetype_bias": "epic_hero"
    },
    "asmr": {
        "name": "ASMR / Oddly Satisfying",
        "weight": 6,
        "prompt_hint": "Oddly satisfying visuals, close-up textures, slow deliberate movements, sensory pleasure",
        "energy": "very_calm",
        "archetype_bias": "ritual"
    },
    "news": {
        "name": "Breaking News",
        "weight": 4,
        "prompt_hint": "News report parody, urgent announcement, BREAKING headline energy, reporter reveal",
        "energy": "urgent",
        "archetype_bias": "discovery"
    },
    "sports": {
        "name": "Sports Moment",
        "weight": 5,
        "prompt_hint": "Sports highlight reel, victory celebration, champion moment, crowd goes wild",
        "energy": "triumphant",
        "archetype_bias": "epic_hero"
    },
    "horror_reveal": {
        "name": "Horror Reveal",
        "weight": 3,
        "prompt_hint": "Horror movie reveal, dramatic lighting shift, suspense to relief, plot twist moment",
        "energy": "suspenseful",
        "archetype_bias": "discovery"
    },
    "gameshow": {
        "name": "Game Show",
        "weight": 4,
        "prompt_hint": "Game show reveal moment, prize presentation, confetti celebration, winner energy",
        "energy": "exciting",
        "archetype_bias": "discovery"
    }
}


# === SELECTION FUNCTIONS ===

def select_random_style(photorealistic_only: bool = False) -> str:
    """
    Select a random visual style using weighted selection.

    Args:
        photorealistic_only: If True, only select from photorealistic styles
                            (suitable for marketplace, first generations)

    Returns the style key (e.g., "cartoon", "cinematic").
    """
    if photorealistic_only:
        styles = [k for k, v in VISUAL_STYLES.items() if v.get("photorealistic", False)]
    else:
        styles = list(VISUAL_STYLES.keys())

    weights = [VISUAL_STYLES[s]["weight"] for s in styles]
    return random.choices(styles, weights=weights, k=1)[0]


def select_random_kind() -> str:
    """
    Select a random video kind using weighted selection.

    Returns the kind key (e.g., "meme", "standard").
    """
    kinds = list(VIDEO_KINDS.keys())
    weights = [VIDEO_KINDS[k]["weight"] for k in kinds]
    return random.choices(kinds, weights=weights, k=1)[0]


def get_photorealistic_styles() -> List[str]:
    """Get list of photorealistic style keys (marketplace-safe)."""
    return [k for k, v in VISUAL_STYLES.items() if v.get("photorealistic", False)]


def get_artistic_styles() -> List[str]:
    """Get list of artistic/creative style keys (cartoon, anime, etc.)."""
    return [k for k, v in VISUAL_STYLES.items() if not v.get("photorealistic", False)]


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


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


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

    If style_key or kind_key is None, provides a list of available options
    for Claude to choose from based on feedback analysis.

    Returns formatted text for insertion into stage2 prompt.
    """
    # If style is not specified, let Claude choose
    if style_key is None or kind_key is None:
        return get_style_choice_context()

    style = get_style_config(style_key)
    kind = get_kind_config(kind_key)

    context = 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']}

Your story vision MUST incorporate these creative directions:
- Adapt the visual descriptions to match the style (e.g., if cartoon - describe cartoon-like scenes with bold colors and exaggerated expressions)
- Match the energy level to the video kind (e.g., if dance - include movement and rhythm; if ASMR - slow, deliberate, satisfying)
- The archetype can be influenced by kind's archetype_bias but product appropriateness takes priority
"""

    # Add archetype bias hint if present
    if kind.get("archetype_bias"):
        context += f"- Suggested archetype for this kind: {kind['archetype_bias']} (but adapt to product)\n"

    return context


def get_style_choice_context() -> str:
    """
    Generate context for Claude to choose style/kind based on feedback analysis.

    Used when visual_style and video_kind are not pre-specified.
    """
    # Group styles by photorealistic vs artistic
    photo_styles = []
    artistic_styles = []

    for key, config in VISUAL_STYLES.items():
        entry = f"- **{key}**: {config['name']} - {config['prompt_hint'][:80]}..."
        if config.get("photorealistic", False):
            photo_styles.append(entry)
        else:
            artistic_styles.append(entry)

    # Format kinds
    kinds_list = []
    for key, config in VIDEO_KINDS.items():
        kinds_list.append(f"- **{key}**: {config['name']} - {config['prompt_hint'][:60]}... (energy: {config['energy']})")

    context = f"""## Creative Direction - YOU CHOOSE

**IMPORTANT:** Analyze the user feedback and previous generations to decide which visual_style and video_kind to use.

### If user references a specific previous generation:
- Use the SAME visual_style and video_kind from that generation
- Check the "Recent GOOD generations" section for the style info

### Available Visual Styles:

**PHOTOREALISTIC (marketplace-safe, professional look):**
{chr(10).join(photo_styles)}

**ARTISTIC (stylized, creative):**
{chr(10).join(artistic_styles)}

### Available Video Kinds:
{chr(10).join(kinds_list)}

### Your Decision Process:
1. Read all user feedback carefully
2. If user references a previous generation → use that generation's style/kind
3. If user asks for something "new" or "different" → try a different style
4. If no clear preference → use photorealistic style appropriate for the product

Output the chosen style and kind in your JSON response.
"""
    return context


def get_all_style_names() -> List[str]:
    """Get list of all visual style keys."""
    return list(VISUAL_STYLES.keys())


def get_all_kind_names() -> List[str]:
    """Get list of all video kind keys."""
    return list(VIDEO_KINDS.keys())


def select_multiple_styles(
    count: int = 3,
    photorealistic_only: bool = True,
    exclude_styles: List[str] = None,
    exclude_kinds: List[str] = None
) -> List[Tuple[str, str]]:
    """
    Select multiple distinct style/kind combinations for critic evaluation.

    Args:
        count: Number of combinations to select (default 3)
        photorealistic_only: If True, only select from photorealistic styles
        exclude_styles: List of style keys to exclude
        exclude_kinds: List of kind keys to exclude

    Returns:
        List of (style_key, kind_key) tuples, all distinct
    """
    exclude_styles = exclude_styles or []
    exclude_kinds = exclude_kinds or []

    # Get available styles
    if photorealistic_only:
        available_styles = [k for k, v in VISUAL_STYLES.items()
                          if v.get("photorealistic", False) and k not in exclude_styles]
    else:
        available_styles = [k for k in VISUAL_STYLES.keys() if k not in exclude_styles]

    # Get available kinds
    available_kinds = [k for k in VIDEO_KINDS.keys() if k not in exclude_kinds]

    if len(available_styles) < count:
        # If not enough photorealistic, add artistic styles
        available_styles = [k for k in VISUAL_STYLES.keys() if k not in exclude_styles]

    results = []
    used_styles = set()
    used_kinds = set()

    for i in range(count):
        # Select style (prefer unused, but allow repeats if needed)
        style_candidates = [s for s in available_styles if s not in used_styles]
        if not style_candidates:
            style_candidates = available_styles

        style_weights = [VISUAL_STYLES[s]["weight"] for s in style_candidates]
        selected_style = random.choices(style_candidates, weights=style_weights, k=1)[0]
        used_styles.add(selected_style)

        # Select kind (prefer unused, prioritize variety)
        kind_candidates = [k for k in available_kinds if k not in used_kinds]
        if not kind_candidates:
            kind_candidates = available_kinds

        kind_weights = [VIDEO_KINDS[k]["weight"] for k in kind_candidates]
        selected_kind = random.choices(kind_candidates, weights=kind_weights, k=1)[0]
        used_kinds.add(selected_kind)

        results.append((selected_style, selected_kind))

    return results


def format_style_options_for_critic(style_kind_pairs: List[Tuple[str, str]]) -> str:
    """
    Format multiple style/kind options for the critic prompt.

    Returns formatted text describing each option.
    """
    lines = []
    for i, (style_key, kind_key) in enumerate(style_kind_pairs, 1):
        style = get_style_config(style_key)
        kind = get_kind_config(kind_key)

        lines.append(f"""### Option {i}: {style['name']} + {kind['name']}

**Visual Style ({style_key}):** {style['prompt_hint']}
**Video Kind ({kind_key}):** {kind['prompt_hint']}
Energy: {kind['energy']}
{f"Archetype hint: {kind['archetype_bias']}" if kind.get('archetype_bias') else ''}
""")

    return "\n".join(lines)


# === CLAUDE-BASED INTELLIGENT SELECTION ===

# Claude CLI path - check common locations
CLAUDE_CLI = None
for path in ["/home/videobot/.local/bin/claude", os.path.expanduser("~/.local/bin/claude"), "claude"]:
    if os.path.exists(path) or path == "claude":
        CLAUDE_CLI = path
        break


def _call_claude_for_style(prompt: str, timeout: int = 60) -> Optional[str]:
    """Call Claude CLI for style selection (internal helper)."""
    if not CLAUDE_CLI:
        return None

    cmd = [CLAUDE_CLI, "-p"]
    try:
        result = subprocess.run(
            cmd,
            input=prompt,
            capture_output=True,
            text=True,
            timeout=timeout
        )
        if result.returncode == 0:
            return result.stdout.strip()
    except Exception:
        pass
    return None


def _extract_json(text: str) -> Optional[Dict]:
    """Extract JSON from Claude response."""
    import json
    try:
        start = text.find('{')
        end = text.rfind('}') + 1
        if start >= 0 and end > start:
            return json.loads(text[start:end])
    except json.JSONDecodeError:
        pass
    return None


def select_style_with_claude(
    feedback_comments: List[str],
    previous_style: Optional[str],
    previous_kind: Optional[str],
    last_rating: Optional[str],
    product_category: Optional[str] = None,
    generation_attempt: int = 1
) -> Tuple[str, str, str]:
    """
    Use Claude to analyze feedback and select best style/kind.

    Args:
        feedback_comments: List of user comments from previous generations
        previous_style: Style used in previous generation (or None)
        previous_kind: Kind used in previous generation (or None)
        last_rating: Rating of previous generation ("good", "bad", "artifacts", or None)
        product_category: Product category if known
        generation_attempt: Which attempt this is (1-2 = prefer photorealistic, 3+ = any)

    Returns:
        Tuple of (visual_style, video_kind, reason)
    """
    # Build available styles list with photorealistic/artistic markers
    photorealistic = get_photorealistic_styles()
    artistic = get_artistic_styles()
    kind_names = ", ".join(get_all_kind_names())

    # Determine if we should prefer photorealistic
    prefer_photorealistic = generation_attempt <= 2

    prompt = f"""Analyze user feedback and select the best visual style and video kind for the next video generation.

## Previous Generation
- Visual Style: {previous_style or "None (first generation)"}
- Video Kind: {previous_kind or "None (first generation)"}
- Rating: {last_rating or "None (first generation)"}
- Product Category: {product_category or "Unknown"}
- Generation Attempt: {generation_attempt}

## User Feedback
{chr(10).join(feedback_comments) if feedback_comments else "No comments provided"}

## Available Visual Styles

**PHOTOREALISTIC (marketplace-safe, prefer for early attempts):**
{", ".join(photorealistic)}

**ARTISTIC/CREATIVE (cartoon, anime, etc. - use on attempt 3+ or if user requests):**
{", ".join(artistic)}

## Available Video Kinds
{kind_names}

## Rules
1. **IMPORTANT**: For attempts 1-2, PREFER photorealistic styles (cinematic, noir, western, horror, retro_50s) - they look professional on marketplace
2. Use artistic styles (cartoon, anime, comic_book, etc.) ONLY if:
   - This is attempt 3 or later
   - User EXPLICITLY requests cartoon/anime/creative style in feedback
   - Previous photorealistic attempts were rated bad
3. If rating was "good" and no style change requested -> keep same style/kind
4. If rating was "bad" or "artifacts" -> try something DIFFERENT from previous
5. If user mentions specific style/mood in feedback -> follow their direction (overrides rule 1-2)
6. Keywords to detect in Russian feedback (these override photorealistic preference):
   - "мультяшный/мультик/мультфильм" -> cartoon style
   - "аниме" -> anime style
   - "комикс" -> comic_book style
   - "пиксар/3д" -> 3d_pixar style
   - "киберпанк/неон" -> cyberpunk style

Current preference: {"PHOTOREALISTIC (attempt " + str(generation_attempt) + ")" if prefer_photorealistic else "ANY STYLE (attempt " + str(generation_attempt) + ")"}

## Output (JSON only, no other text)
{{"visual_style": "...", "video_kind": "...", "reason": "brief explanation"}}
"""

    response = _call_claude_for_style(prompt)
    if response:
        result = _extract_json(response)
        if result:
            style = result.get("visual_style", "cinematic")
            kind = result.get("video_kind", "standard")
            reason = result.get("reason", "Claude selection")

            # Validate selections
            if style not in VISUAL_STYLES:
                style = "cinematic"
            if kind not in VIDEO_KINDS:
                kind = "standard"

            return (style, kind, reason)

    # Fallback to random if Claude fails (prefer photorealistic for early attempts)
    use_photorealistic = generation_attempt <= 2
    return (
        select_random_style(photorealistic_only=use_photorealistic),
        select_random_kind(),
        f"Random fallback - {'photorealistic' if use_photorealistic else 'any style'} (Claude unavailable)"
    )


def select_style_from_feedback(
    feedback: Optional[Dict],
    first_generation: bool = False,
    generation_attempt: int = 1
) -> Tuple[str, str, str]:
    """
    Select style/kind based on feedback context.

    Args:
        feedback: Feedback dict from load_product_feedback() or None
        first_generation: True if this is the first generation for the product
        generation_attempt: Which attempt this is (1 = first, 2+ = retries)

    Returns:
        Tuple of (visual_style, video_kind, reason)

    Style Selection Strategy:
    - First attempts (1-2): Use photorealistic styles (marketplace-safe)
    - Later attempts (3+): Can use artistic styles (cartoon, anime, etc.)
    - User request: Always honor explicit style requests in feedback
    """
    if first_generation or not feedback:
        # First generation - use photorealistic styles for marketplace
        style = select_random_style(photorealistic_only=True)
        kind = select_random_kind()
        return (style, kind, "Photorealistic style (first generation, marketplace-safe)")

    # Extract info from feedback
    bad_gens = feedback.get("bad_generations", [])
    good_gens = feedback.get("good_generations", [])

    # Get previous generation info
    all_gens = bad_gens + good_gens
    if not all_gens:
        style = select_random_style()
        kind = select_random_kind()
        return (style, kind, "Random selection (no rated generations)")

    # Get most recent generation
    recent = all_gens[-1] if all_gens else {}

    previous_style = recent.get("visual_style")
    previous_kind = recent.get("video_kind")
    last_rating = "bad" if recent in bad_gens else "good"

    # Collect all comments
    comments = []
    for gen in all_gens:
        if gen.get("comment"):
            comments.append(gen["comment"])

    # Calculate generation attempt (how many generations have been made + 1)
    attempt = len(all_gens) + 1 if generation_attempt <= 1 else generation_attempt

    # Use Claude for intelligent selection
    return select_style_with_claude(
        feedback_comments=comments,
        previous_style=previous_style,
        previous_kind=previous_kind,
        last_rating=last_rating,
        product_category=recent.get("category"),
        generation_attempt=attempt
    )


# === DISPLAY HELPERS ===

def format_style_for_caption(style_key: str, kind_key: str) -> str:
    """
    Format style/kind for Telegram caption display.

    Returns string like "Cartoon | Meme"
    """
    style = get_style_config(style_key)
    kind = get_kind_config(kind_key)
    return f"{style['name']} | {kind['name']}"


def get_style_emoji(style_key: str) -> str:
    """Get emoji for visual style."""
    emoji_map = {
        "cinematic": "🎬",
        "cartoon": "🖍",
        "anime": "🇯🇵",
        "retro_50s": "📺",
        "noir": "🎩",
        "comic_book": "💥",
        "3d_pixar": "🧸",
        "cyberpunk": "🌃",
        "vaporwave": "🌴",
        "steampunk": "⚙️",
        "western": "🤠",
        "horror": "👻",
        "art_deco": "🥂",
        "pop_art": "🎨",
        "ukiyo_e": "🗾",
        "watercolor": "💧",
        "chibi": "🥺",
        "gothic": "🦇",
        "surreal": "🎪",
        "pixel_art": "👾",
        # New Russian/Soviet styles
        "soviet_retro": "☭",
        "russian_fairy_tale": "🪆",
        "russian_silver_age": "🎭",
        "russian_aristocracy": "👑",
        "soviet_constructivism": "🔴",
        "stalinist_empire": "🏛️",
        # Fashion styles
        "fashion_runway": "👠",
        "disco": "🪩",
        # Music/subculture styles
        "rock_concert": "🎸",
        "punk": "🤘",
        "hip_hop": "🎤",
        "grunge": "🎵",
        "glam_rock": "✨",
        "rave": "🌈"
    }
    return emoji_map.get(style_key, "🎨")


def get_kind_emoji(kind_key: str) -> str:
    """Get emoji for video kind."""
    emoji_map = {
        "standard": "📦",
        "meme": "😂",
        "dance": "💃",
        "superhero": "🦸",
        "action_movie": "💥",
        "romance": "💕",
        "fairy_tale": "✨",
        "thriller": "😰",
        "circus": "🎪",
        "infomercial": "📺",
        "unboxing": "📦",
        "documentary": "🎥",
        "standup": "🎤",
        "asmr": "🤫",
        "news": "📰",
        "sports": "🏆",
        "horror_reveal": "😱",
        "gameshow": "🎰"
    }
    return emoji_map.get(kind_key, "🎭")


if __name__ == "__main__":
    # Test selections
    print("=== Visual Styles Library ===")
    print(f"Total styles: {len(VISUAL_STYLES)}")
    print(f"Total kinds: {len(VIDEO_KINDS)}")
    print(f"Possible combinations: {len(VISUAL_STYLES) * len(VIDEO_KINDS)}")
    print()

    print("=== Random Selection Test ===")
    for i in range(5):
        style = select_random_style()
        kind = select_random_kind()
        style_cfg = get_style_config(style)
        kind_cfg = get_kind_config(kind)
        print(f"  {i+1}. {get_style_emoji(style)} {style_cfg['name']} | {get_kind_emoji(kind)} {kind_cfg['name']}")
    print()

    print("=== Style Prompt Context Example ===")
    print(get_style_prompt_context("cartoon", "meme")[:500] + "...")
