
from typing import Dict, Any, List, Optional
from app.config import settings

# ==========================================
# CONSTANTS & DATA
# ==========================================

CAMERA_DATA = [
    {
        "value": "Arri Alexa 35",
        "display": "Arri Alexa 35",
        "sensorFormat": "Super 35",
        "tooltip": "The Hollywood Standard. Best for natural skin tones and a classic cinematic 'blockbuster' feel.",
        "tags": "Narrative / Drama",
        "compatibleLenses": ["Panavision C-Series", "Cooke S7/i", "Canon K-35", "Laowa Probe"],
        "physics": "ArriRaw sensor readout, high dynamic range, natural noise floor, thick color science"
    },
    {
        "value": "Sony Venice 2",
        "display": "Sony Venice 2",
        "sensorFormat": "Full Frame",
        "tooltip": "The Low-Light King. Excellent for night scenes, clean shadows, and a modern aesthetic.",
        "tags": "Commercial / Night",
        "compatibleLenses": ["Panavision C-Series", "Cooke S7/i", "Canon K-35", "Arri Signature", "Laowa Probe"],
        "physics": "Dual ISO digital sensor, clean shadows, modern color science, high frequency detail"
    },
    {
        "value": "Red V-Raptor",
        "display": "Red V-Raptor",
        "sensorFormat": "Full Frame",
        "tooltip": "Hyper-Real Action. Perfect for high-speed motion, sports, and razor-sharp detail.",
        "tags": "Action / Sports",
        "compatibleLenses": ["Panavision C-Series", "Cooke S7/i", "Canon K-35", "Arri Signature", "Laowa Probe"],
        "physics": "RedCode RAW 8K, clinical sharpness, high shutter angle clarity, hyper-realistic texture"
    },
    {
        "value": "Arriflex 416",
        "display": "Arriflex 416",
        "sensorFormat": "Super 16 (Film)",
        "tooltip": "Gritty & Nostalgic. High grain, soft focus, and vibrant, messy colors. The 'Indie' look.",
        "tags": "Vintage / Music Video",
        "compatibleLenses": ["Zeiss Super Speed", "Laowa Probe"],
        "physics": "Super 16mm film gate, heavy grain structure, soft optical resolution, vibrant chemical color"
    },
    {
        "value": "Arricam LT",
        "display": "Arricam LT",
        "sensorFormat": "35mm (Film)",
        "tooltip": "The Golden Age. Fine grain, organic texture, and rich colors. The classic movie look before digital.",
        "tags": "Period Piece / Premium",
        "compatibleLenses": ["Panavision C-Series", "Cooke S7/i", "Canon K-35", "Laowa Probe"],
        "physics": "35mm motion picture film stock, organic grain structure, halation on highlights, photochemical dynamic range"
    },
    {
        "value": "Fujifilm GFX 100",
        "display": "Fujifilm GFX 100",
        "sensorFormat": "Medium Format",
        "tooltip": "The Studio Master. Massive resolution and depth. Unbeatable for print-quality stills.",
        "tags": "Product / Fashion",
        "compatibleLenses": ["Fujinon GF", "Arri Signature", "Laowa Probe"],
        "physics": "Medium format digital sensor, zero circle of confusion, extreme resolution, pore-level detail"
    },
    {
        "value": "Phantom Flex4K",
        "display": "Phantom Flex4K",
        "sensorFormat": "Super 35",
        "tooltip": "The Time Machine. 1000fps slow motion.",
        "tags": "High-Speed / Sports",
        "compatibleLenses": ["Panavision C-Series", "Cooke S7/i", "Canon K-35", "Laowa Probe", "Angénieux Optimo"],
        "physics": "High-speed global shutter sensor, frozen fluid dynamics, zero motion blur, deep saturation, specialized for 1000fps playback"
    },
    {
        "value": "Blackmagic URSA Cine 12K",
        "display": "URSA Cine 12K",
        "sensorFormat": "Full Frame",
        "tooltip": "Resolution Monster. Infinite reframing capability.",
        "tags": "Future-Proof / VFX",
        "compatibleLenses": ["Panavision C-Series", "Cooke S7/i", "Canon K-35", "Arri Signature", "Laowa Probe", "Canon TS-E", "Angénieux Optimo"],
        "physics": "12K RGB sensor, extreme resolution, zero aliasing, distinct non-bayer pattern texture, analytics-grade sharpness"
    }
]

LENS_DATA = [
    {
        "value": "Panavision C-Series",
        "display": "Panavision C-Series",
        "compatibleFormats": ["Super 35", "35mm"],
        "tooltip": "Classic Widescreen. Horizontal blue flares, oval bokeh. The sci-fi blockbuster look.",
        "keywords": "Flares, Oval Bokeh",
        "physics": "anamorphic optics, characteristic oval bokeh, horizontal blue lens flares, slight barrel distortion"
    },
    {
        "value": "Cooke S7/i",
        "display": "Cooke S7/i",
        "compatibleFormats": ["Full Frame", "Super 35", "35mm"],
        "tooltip": "The 'Cooke Look.' Warm, gentle, and incredibly flattering. Gold standard for portraits.",
        "keywords": "Warmth, Face Focus",
        "physics": "Cooke speed panchrio look, warm color rendering, gentle focus falloff, flattering face compression"
    },
    {
        "value": "Canon K-35",
        "display": "Canon K-35",
        "compatibleFormats": ["Full Frame", "Super 35", "35mm"],
        "tooltip": "Dreamy & Retro. Low contrast, glowing highlights. 1970s/80s vibe.",
        "keywords": "Glow, Retro",
        "physics": "vintage aspherical elements, glowing highlights, low contrast, rainbow flaring, soft sharpness"
    },
    {
        "value": "Arri Signature",
        "display": "Arri Signature",
        "compatibleFormats": ["Large Format", "Full Frame"],
        "tooltip": "Modern Perfection. Ultra-clean, no distortion, pure reality. The invisible lens.",
        "keywords": "Clean, Realistic",
        "physics": "telecentric optical design, zero breathing, ultra-flat field, modern rendering, pure black levels"
    },
    {
        "value": "Zeiss Super Speed",
        "display": "Zeiss Super Speed",
        "compatibleFormats": ["Super 16 ONLY"],
        "tooltip": "The 16mm Classic. Sharp but textured. Designed specifically for the smaller 16mm film frame.",
        "keywords": "Triangular Bokeh, Grit",
        "physics": "vintage high-speed glass, triangular bokeh at wide apertures, chromatic aberration, gritty texture"
    },
    {
        "value": "Fujinon GF",
        "display": "Fujinon GF",
        "compatibleFormats": ["Medium Format ONLY"],
        "tooltip": "Studio Glass. Clinically sharp, specifically designed for the massive GFX sensor.",
        "keywords": "Clinical Sharpness",
        "physics": "modern medium format optics, clinical edge-to-edge sharpness, zero distortion, high micro-contrast"
    },
    {
        "value": "Laowa Probe",
        "display": "Laowa Probe",
        "compatibleFormats": ["All Formats"],
        "tooltip": "Insect-Eye View. Extreme close-ups of small objects/textures.",
        "keywords": "Macro",
        "physics": "macro bug-eye perspective, extreme depth of field, tubular lens construction, surreal wide-angle macro"
    },
    {
        "value": "Helios 44-2",
        "display": "Helios 44-2 (Vintage)",
        "compatibleFormats": ["Full Frame", "Super 35", "35mm"],
        "tooltip": "Swirly Bokeh. The cult classic.",
        "keywords": "Swirly Bokeh, Vintage",
        "physics": "Vintage Soviet glass, characteristic swirly bokeh at edges, low contrast flaring, soft center focus, dreamlike aberrations"
    },
    {
        "value": "Canon TS-E",
        "display": "Canon Tilt-Shift",
        "compatibleFormats": ["Full Frame", "Medium Format"],
        "tooltip": "Miniature Effect. Selective focus control.",
        "keywords": "Tilt-Shift, Miniature",
        "physics": "Tilted focal plane, miniature faking effect, selective focus slice, corrected perspective lines, architectural rigidity"
    },
    {
        "value": "Angénieux Optimo",
        "display": "Angénieux Optimo",
        "compatibleFormats": ["Super 35", "Full Frame"],
        "tooltip": "The Hollywood Zoom. Perfect versatility.",
        "keywords": "Cinema Zoom",
        "physics": "Cinema zoom optics, warm organic contrast, breathing-free focus pulls, uniform field illumination"
    }
]

APPLICATION_DATA = [
    {
        "value": "Portrait Studio",
        "lighting": "Rembrandt lighting, softbox diffusion, 3-point setup",
        "defaultCamera": "Arri Alexa 35",
        "defaultLens": "Cooke S7/i",
        "focusType": "stylistic"
    },
    {
        "value": "Product (Crisp)",
        "lighting": "Infinity curve, bright diffuse lighting, shadowless, high key",
        "defaultCamera": "Fujifilm GFX 100",
        "defaultLens": "Fujinon GF",
        "focusType": "realism"
    },
    {
        "value": "Food Photography",
        "lighting": "Natural window light simulation, back-lighting for steam/texture, warm reflector fill, medium depth of field, focus on texture",
        "defaultCamera": "Sony Venice 2",
        "defaultLens": "Cooke S7/i",
        "focusType": "stylistic"
    },
    {
        "value": "Golden Hour (Outdoor)",
        "lighting": "Sun low on horizon, warm orange glow, long dramatic shadows, volumetric backlight, magic hour atmosphere, cinematic depth",
        "defaultCamera": "Arricam LT",
        "defaultLens": "Cooke S7/i",
        "focusType": "stylistic",
        "example": "A vintage Lancia Stratos rally car drifting sideways on a dirt track, kicking up a massive wall of dust that glows incandescent gold in the backlight, creating a dramatic silhouette against the sunset."
    },
    {
        "value": "Blue Hour (City)",
        "lighting": "Twilight, deep blue ambient sky light contrasting with warm practical street lamps, moody, atmospheric, balanced exposure",
        "defaultCamera": "Sony Venice 2",
        "defaultLens": "Arri Signature",
        "focusType": "stylistic"
    },
    {
        "value": "Neon Cyberpunk",
        "lighting": "Harsh neon signage, mixed color temp, wet reflections",
        "defaultCamera": "Red V-Raptor",
        "defaultLens": "Panavision C-Series",
        "focusType": "stylistic"
    },
    {
        "value": "Nostalgic Memory",
        "lighting": "Hazy atmosphere, overexposed highlights, light leaks, warm color grade, sentimental mood, soft focus throughout",
        "defaultCamera": "Arriflex 416",
        "defaultLens": "Zeiss Super Speed",
        "focusType": "stylistic"
    },
    {
        "value": "Corporate Headshot",
        "lighting": "Clean white background, high-key lighting, professional balanced fill, sharp focus on eyes, moderate depth of field",
        "defaultCamera": "Fujifilm GFX 100",
        "defaultLens": "Cooke S7/i",
        "focusType": "realism"
    },
    {
        "value": "Macro: Luxury Jewelry",
        "lighting": "Sparkling point-source lighting, black velvet background, high contrast reflection control, focus stacking simulation for complete sharpness",
        "defaultCamera": "Fujifilm GFX 100",
        "defaultLens": "Laowa Probe",
        "focusType": "realism"
    },
    {
        "value": "Macro: Nature Details",
        "lighting": "Diffused natural sunlight, shallow depth of field, vibrant greens, morning dew, microscopic texture",
        "defaultCamera": "Arri Alexa 35",
        "defaultLens": "Laowa Probe",
        "focusType": "stylistic"
    },
    {
        "value": "Wildlife / Safari",
        "lighting": "Telephoto compression, frozen motion, golden hour backlight, natural habitat, separation from background",
        "defaultCamera": "Red V-Raptor",
        "defaultLens": "Cooke S7/i",
        "focusType": "stylistic"
    },
    {
        "value": "Sports Action",
        "lighting": "High shutter speed, frozen particles/sweat, stadium floodlights, dynamic composition, sharp subject focus",
        "defaultCamera": "Red V-Raptor",
        "defaultLens": "Panavision C-Series",
        "focusType": "stylistic"
    },
    {
        "value": "Street Photography",
        "lighting": "Candid moment, natural available light, messy urban background, hyperfocal distance, deep depth of field, everything in focus",
        "defaultCamera": "Arriflex 416",
        "defaultLens": "Canon K-35",
        "focusType": "realism"
    },
    {
        "value": "Architecture",
        "lighting": "Balanced mixed lighting, straight lines, airy atmosphere",
        "defaultCamera": "Fujifilm GFX 100",
        "defaultLens": "Fujinon GF",
        "focusType": "realism"
    },
    {
        "value": "Fashion Editorial",
        "lighting": "Avant-garde lighting, colored gels, stark shadows, high fashion pose, studio backdrop, stylized depth",
        "defaultCamera": "Sony Venice 2",
        "defaultLens": "Canon K-35",
        "focusType": "stylistic"
    },
    {
        "value": "Cinematic Horror",
        "lighting": "Underexposed, single harsh source (flashlight), heavy shadows",
        "defaultCamera": "Arricam LT",
        "defaultLens": "Canon K-35",
        "focusType": "stylistic"
    },
    {
        "value": "Docu / Realism",
        "lighting": "Natural window key light, negative fill, messy authentic background",
        "defaultCamera": "Arri Alexa 35",
        "defaultLens": "Arri Signature",
        "focusType": "realism"
    },
    {
        "value": "Symmetrical Whimsy",
        "lighting": "Shadowless high-key lighting, flat diorama aesthetic, vibrant pastel color palette, 90-degree planimetric composition",
        "defaultCamera": "Arricam LT",
        "defaultLens": "Cooke S7/i",
        "focusType": "stylistic"
    },
    {
        "value": "IMAX Scale Epic",
        "lighting": "Naturalistic practical lighting, cool color temperature, high contrast, immense sense of scale, deep depth of field",
        "defaultCamera": "Arri Alexa 35",
        "defaultLens": "Arri Signature",
        "focusType": "realism"
    },
    {
        "value": "Clinical Thriller",
        "lighting": "Low-key chiaroscuro, controlled shadows, sickly green/yellow color grade, precise stabilized motion",
        "defaultCamera": "Red V-Raptor",
        "defaultLens": "Arri Signature",
        "focusType": "stylistic"
    },
    {
        "value": "Brutalist Atmosphere",
        "lighting": "Single source silhouette, atmospheric haze, monochromatic orange/sepia tones, stark geometry, visual silence",
        "defaultCamera": "Arri Alexa 35",
        "defaultLens": "Panavision C-Series",
        "focusType": "stylistic"
    },
    {
        "value": "Technicolor Dream",
        "lighting": "Artificial studio lighting, high saturation, vibrant pinks and cyans, glossy plastic textures, high-key brightness",
        "defaultCamera": "Arri Alexa 35",
        "defaultLens": "Cooke S7/i",
        "focusType": "stylistic"
    },
    {
        "value": "Obsessive Symmetry",
        "lighting": "One-point perspective, deep focus, wide angle distortion, cold practical lighting, clinical perfection",
        "defaultCamera": "Arricam LT",
        "defaultLens": "Arri Signature",
        "focusType": "realism"
    },
    {
        "value": "Hong Kong Nostalgia",
        "lighting": "Step-printing effect, motion blur, neon-soaked humidity, intimate handheld, rain-slicked textures",
        "defaultCamera": "Arriflex 416",
        "defaultLens": "Zeiss Super Speed",
        "focusType": "stylistic"
    },
    {
        "value": "Industrial Haze",
        "lighting": "Volumetric lighting, visible shafts of light (god rays), atmospheric haze, high-density industrial detail",
        "defaultCamera": "Arri Alexa 35",
        "defaultLens": "Panavision C-Series",
        "focusType": "stylistic"
    },
    {
        "value": "Gothic Fantasy",
        "lighting": "German Expressionist lighting, high contrast long shadows, twisted geometry, desaturated palette",
        "defaultCamera": "Arri Alexa 35",
        "defaultLens": "Panavision C-Series",
        "focusType": "stylistic"
    },
    {
        "value": "LED Volume (Virtual Production)",
        "lighting": "Interactive environmental lighting, soft ambient wrap from LED panels, perfect reflection matching, zero green spill",
        "defaultCamera": "Arri Alexa 35",
        "defaultLens": "Arri Signature",
        "focusType": "realism"
    },
    {
        "value": "Automotive: Showroom",
        "lighting": "Massive softbox ceiling, continuous highlight lines along bodywork, negative fill to shape curves, pure white infinity cove",
        "defaultCamera": "Sony Venice 2",
        "defaultLens": "Arri Signature",
        "focusType": "realism",
        "example": "A silver concept car parked on a pure white infinity curve, continuous highlight lines tracing the aerodynamic bodywork."
    },
    {
        "value": "Knolling / Flat Lay",
        "lighting": "Overhead soft diffuse light, shadowless cavity, high-key evenness, precise grid alignment",
        "defaultCamera": "Fujifilm GFX 100",
        "defaultLens": "Fujinon GF",
        "focusType": "realism"
    },
    {
        "value": "Conflict Photography",
        "lighting": "Harsh midday sun, atmospheric dust and smoke, high contrast, documentary style reality, blown highlights, raw and unpolished",
        "defaultCamera": "Arriflex 416",
        "defaultLens": "Zeiss Super Speed",
        "focusType": "realism"
    },
    {
        "value": "NYC Street Editorial",
        "lighting": "Natural city canyon light, bounce board fill for face, sharp modern contrast, motion blur in background, high-resolution gloss",
        "defaultCamera": "Sony Venice 2",
        "defaultLens": "Arri Signature",
        "focusType": "stylistic"
    },
    {
        "value": "Underground Rave / Flash",
        "lighting": "Direct on-camera flash with slow shutter drag (rear-curtain sync), light trails, laser rim lighting, sweaty atmosphere, darkness crushing the background",
        "defaultCamera": "Red V-Raptor",
        "defaultLens": "Helios 44-2",
        "focusType": "stylistic"
    },
    {
        "value": "Architectural Digest Interior",
        "lighting": "North-facing window soft light, large diffusion frames, negative fill for contrast, texture-raking angle, perfectly balanced exposure",
        "defaultCamera": "Fujifilm GFX 100",
        "defaultLens": "Canon TS-E",
        "focusType": "realism"
    },
    {
        "value": "90s Grunge Editorial",
        "lighting": "Hard direct flash, dirty green/yellow color cast, vignetting, unretouched skin texture, claustrophobic framing",
        "defaultCamera": "Arriflex 416",
        "defaultLens": "Canon K-35",
        "focusType": "stylistic"
    },
    {
        "value": "Cassette Futurism (Retro Sci-Fi)",
        "lighting": "Flickering CRT monitor glow, harsh overhead fluorescent strips, brutalist shadows, beige and grey color palette, industrial haze",
        "defaultCamera": "Arriflex 416",
        "defaultLens": "Panavision C-Series",
        "focusType": "stylistic"
    },
    {
        "value": "Tech Commercial (Macro)",
        "lighting": "Slow moving light sweep (motion control), brushed metal reflections, dramatic rim lighting in a black void, sub-surface scattering on materials",
        "defaultCamera": "Arri Alexa 35",
        "defaultLens": "Laowa Probe",
        "focusType": "realism"
    },
    {
        "value": "Surreal Infrared",
        "lighting": "Full spectrum daylight, false color infrared shift (foliage turns pink/white), deep blue skies, high contrast, dreamlike atmosphere",
        "defaultCamera": "Arricam LT",
        "defaultLens": "Canon K-35",
        "focusType": "stylistic"
    },
    {
        "value": "Spaghetti Western",
        "lighting": "Harsh high-noon sun, heat haze distortion, sweaty skin texture, extreme close-up on eyes, deep depth of field",
        "defaultCamera": "Arricam LT",
        "defaultLens": "Angénieux Optimo",
        "focusType": "stylistic"
    },
    {
        "value": "Automotive: Process Trailer",
        "lighting": "Dynamic passing street lights, rhythmic shadow movement, wet road reflections, motion blur on background only",
        "defaultCamera": "Arri Alexa 35",
        "defaultLens": "Angénieux Optimo",
        "focusType": "stylistic",
        "example": "A black sports car speeding through a tunnel, dynamic motion blur on the tunnel lights, sharp focus on the car badge."
    },
    {
        "value": "Product (Liquid/Splash)",
        "lighting": "High-speed strobe lighting, frozen droplets, backlit fluid translucency, crystal clear refraction",
        "defaultCamera": "Phantom Flex4K",
        "defaultLens": "Laowa Probe",
        "focusType": "stylistic",
        "example": "A strawberry dropping into milk, creating a perfect crown splash, frozen in mid-air with high-speed strobe lighting."
    },
    {
        "value": "VFX / Green Screen",
        "lighting": "Raw chromakey plate, perfectly flat shadowless green background, distinct rim light for separation, zero color spill, high-fidelity capture",
        "defaultCamera": "Blackmagic URSA Cine 12K",
        "defaultLens": "Arri Signature",
        "focusType": "realism",
        "example": "A raw chromakey plate of a superhero in a landing pose, completely isolated against a flat, pure digital green background, sharp focus, ready for compositing."
    },
    {
        "value": "Custom",
        "lighting": "User-defined lighting setup",
        "defaultCamera": None,
        "defaultLens": None,
        "focusType": "stylistic"
    }
]

# Aspect Ratio Map (Frontend -> Prose)
ASPECT_RATIO_PROSE = {
    '16:9': 'A cinematic 16:9 composition featuring',
    '2.39:1': 'A widescreen anamorphic-ratio composition featuring',
    '4:3': 'A classic 4:3 format composition featuring',
    '1:1': 'A square format composition featuring',
    '9:16': 'A vertical full-screen composition featuring'
}

# Negative Constraints
CONSTRAINT_MAP = {
    'Architecture': 'Strictly AVOID: messy, dirt, grime, imperfections, motion blur, handheld, shaky',
    'Product (Crisp)': 'Strictly AVOID: messy, dirt, grime, imperfections, motion blur, handheld, shaky',
    'Corporate Headshot': 'Strictly AVOID: shadow over eyes, silhouette, dark, moody, gritty, high contrast',
    'Portrait Studio': 'Strictly AVOID: shadow over eyes, silhouette, dark, moody, gritty, high contrast',
    'Cinematic Horror': 'Strictly AVOID: bright, cheerful, clean, pristine, high-key, sunshine',
    'Nostalgic Memory': 'Strictly AVOID: bright, cheerful, clean, pristine, high-key, sunshine'
}

# Smart Fill Context
SMART_FILL_CONTEXT = {
    'Neon Cyberpunk': 'Hovering vehicle, rain, neon lights',
    'Golden Hour (Outdoor)': 'Vintage convertible, dust kicking up, lens flare',
    'Cinematic Horror': 'Distressed clothing, expressions of terror, flashlight beams cutting through fog, unseen threat in shadows',
    'Corporate Headshot': 'Business professional attire, confident posture, subtle smile, perfectly groomed',
    'Portrait Studio': 'Professional studio setup, controlled lighting, posed subject',
    'Fashion Editorial': 'High fashion couture, avant-garde styling, dramatic poses, editorial expression',
    'Street Photography': 'Authentic street fashion, candid moments, urban environment, real people',
    'Blue Hour (City)': 'Urban nightlife fashion, city lights reflecting, atmospheric fog, metropolitan energy',
    'Wildlife / Safari': 'Natural habitat, majestic animals, golden savanna light, environmental storytelling',
    'Symmetrical Whimsy': 'Perfectly centered vintage car, pastel luggage on roof, quirkily dressed driver',
    'IMAX Scale Epic': 'Lone rover traversing massive alien glacier, tiny against the landscape',
    'Clinical Thriller': 'Sterile hospital corridor, flickering fluorescent light, solitary figure',
    'Brutalist Atmosphere': 'Concrete monolith, lone figure dwarfed by structure, dust particles',
    'Technicolor Dream': 'Plastic fantastic furniture, bubble machines, candy-colored wardrobe',
    'Obsessive Symmetry': 'Identical twins in matching outfits, geometric patterns, perfect alignment',
    'Hong Kong Nostalgia': 'Taxi in heavy rain, neon lights reflecting on wet glass, lonely passenger',
    'Industrial Haze': 'Factory interior, steam pipes, worker silhouette against machinery',
    'Gothic Fantasy': 'Twisted architecture, dramatic cape, fog machine atmosphere'
}

# ==========================================
# HELPER FUNCTIONS
# ==========================================

def get_aspect_ratio_prose(ratio: str) -> str:
    return ASPECT_RATIO_PROSE.get(ratio, '')

def get_negative_constraints(app_name: str) -> str:
    return CONSTRAINT_MAP.get(app_name, '')

def get_smart_fill_context(app_name: str) -> str:
    return SMART_FILL_CONTEXT.get(app_name, '')

def get_camera_texture_keywords(camera_name: str) -> str:
    for cam in CAMERA_DATA:
        if cam["value"] == camera_name:
            return cam["physics"]
    return ""

def get_lens_physics(lens_name: str) -> str:
    for le in LENS_DATA:
        if le["value"] == lens_name:
            return le["physics"]
    return ""

def get_app_data(app_name: str) -> Optional[Dict]:
    for app in APPLICATION_DATA:
        if app["value"] == app_name:
            return app
    return None

# ==========================================
# CINE PROMPT LOGIC
# ==========================================

async def enhance_cine_prompt(
    prompt: str,
    application: str,
    camera: str,
    lens: str,
    aspect_ratio: str,
    creative_freedom: float,
    language: str = "en"
) -> Dict[str, Any]:
    """
    Generate the 'CinePrompt' high-fidelity prompt using Gemini.
    Replicates the 'CinePromptStudio.jsx' logic on the backend.
    """
    import google.generativeai as genai
    
    if not settings.google_api_key:
         return {"note": "Google API Key missing for CinePrompt"}

    try:
        genai.configure(api_key=settings.google_api_key)
        # Use the most capable model
        model = genai.GenerativeModel("gemini-2.0-flash-exp")

        # Gather context
        app_data = get_app_data(application)
        aspect_ratio_prose = get_aspect_ratio_prose(aspect_ratio)
        negative_constraints = get_negative_constraints(application)
        smart_fill_context = get_smart_fill_context(application)
        camera_physics = get_camera_texture_keywords(camera)
        lens_physics = get_lens_physics(lens)
        word_count = len(prompt.split())

        # Construct System Prompt (The 'Master System Prompt')
        system_prompt = f"""You are an expert Cinematographer and Optical Physicist.
Your goal is to Create a "Thick Description" prompt that emphasizes TEXTURE, ATMOSPHERE, and LIGHT.

INPUT VARIABLES:
- Scene: {prompt}
- Application: {application}
- Camera: {camera}
- Lens: {lens}
- Aspect Ratio Prose: {aspect_ratio_prose}
- Creative Freedom: {creative_freedom}
- Camera Physics: {camera_physics}
- Lens Physics: {lens_physics}

EXECUTION STEPS:

1. **SMART FILL CHECK:**
   - IF input is short ({word_count} words < 10) AND Creative Freedom is High ({creative_freedom} > 0.5):
     INVENT details based on Application: {f'"{smart_fill_context}"' if smart_fill_context else 'Use application context'}.

2. **REALISM vs. STYLE CHECK:**
   {'- Application is Architecture, Product, or Documentary: FORCE Deep Focus. Suppress "bokeh". Describe "clinical sharpness."' if app_data and app_data.get('focusType') == 'realism' else '- Application is Narrative/Portrait: ENHANCE "bokeh", "flares", stylistic elements.'}

3. **SENSORY ENHANCEMENT (THE "DEEP TEXTURE" PASS):**
   - **Skin:** If humans are present, describe skin texture (e.g., "visible pores," "slight sweat sheen," "natural imperfections").
   - **Air:** Describe the air quality (e.g., "humid haze," "crisp winter air," "dust motes in light beams").
   - **Light:** Describe the *quality* of light (e.g., "diffused window light," "specular highlights").
   - **Camera Sensor Physics:** Apply these characteristics: "{camera_physics}"

4. **OPTICAL CHARACTERISTICS:**
   - **Lens Physics:** Apply these optical traits: "{lens_physics}"

5. **ASSEMBLY:**
   - Start with {aspect_ratio_prose}
   - Expand subject with Smart Fill
   - Apply {application} lighting defaults
   - Inject Camera Physics (Sensor/Film Stock characteristics)
   - Finish with Lens Physics (Optical characteristics)

OUTPUT FORMAT:
[Aspect Ratio Prose] + [Visual Subject] + [Sensory Atmosphere & Light] + [Camera Physics] + [Lens Physics].

STRICT OUTPUT FORMAT: Return ONLY the final visual description text. Do not use Markdown formatting. Do not include conversational filler.
{"Output in " + language if language != "en" else ""}
"""
        
        # Generate
        response = model.generate_content(system_prompt)
        enhanced_text = response.text.strip()
        
        return {
            "enhanced_prompt": enhanced_text,
            "negative_prompt": negative_constraints or "blurry, low quality, distorted, bad composition",
            "style": application,
            "technical_params": {
                "camera": camera,
                "lens": lens,
                "aspect_ratio": aspect_ratio
            }
        }

    except Exception as e:
        return {"note": f"CinePrompt enhancement failed: {str(e)}"}
