"""Model-aware LLM system prompt builder for banner generation.

Generates Pixar-quality 3D comic strip prompts (4-panel 2x2 grid)
optimised for each image model family (DALL-E / Gemini).
"""

from __future__ import annotations

from .presets import BannerStyle, ImageModelFamily


# ── Per-family prompt rules ───────────────────────────────────────────────────

_RULES_DALLE = """\
## Target model: DALL-E 3 / gpt-image-1
- Write in natural language sentences — NOT comma-separated keyword lists
- Embed negative constraints directly in the prompt text
- Do NOT use Stable Diffusion weight syntax like (word:1.5) — unsupported
- Optimal length: 200–300 words
- Front-load the most important subject/concept in the first sentence
- Be explicit about colors, lighting, and composition
"""

_RULES_GEMINI = """\
## Target model: Google Gemini image generation (gemini-2.5-flash-image, gemini-3-pro-image)
- Write in natural language sentences — Gemini follows narrative descriptions closely
- Gemini excels at complex scenes with multiple elements — be specific about spatial relationships
- Gemini handles long prompts well — 200–300 words is optimal
- Front-load the primary concept in the first sentence
- Specify lighting explicitly — Gemini is very responsive to lighting descriptions
- Use color hex codes for precision: "electric blue (#0066FF) accent glow"
- Gemini has strong style adherence — name the art style explicitly:
  "rendered in Pixar 3D animation style", "isometric 3D illustration", etc.
"""

_RULES_UNKNOWN = _RULES_DALLE

_FAMILY_RULES: dict[ImageModelFamily, str] = {
    ImageModelFamily.DALLE:   _RULES_DALLE,
    ImageModelFamily.GEMINI:  _RULES_GEMINI,
    ImageModelFamily.UNKNOWN: _RULES_UNKNOWN,
}


# ── 4-panel Pixar comic structure ─────────────────────────────────────────────

_COMIC_STRUCTURE = """\
LAYOUT: EXACTLY 4 panels in a 2×2 grid (2 columns, 2 rows). No more, no fewer.
STYLE: Pixar/Disney 3D render quality (like "Inside Out" or "The Incredibles").
Characters: BIG emotive eyes, exaggerated poses, over-the-top reactions. Environments: stylized and vivid.

VISUAL RULES:
- Pixar 3D quality: subsurface scattering, global illumination, rich materials
- Panel colors: Panel 1=dark red-grey chaos, Panel 2=electric blue burst, Panel 3=purple-gold glow, Panel 4=warm green victory
- Each panel has a BOLD PRINTED TITLE in the TOP-LEFT corner only — NOT repeated at the bottom
- Speech bubbles: MAX 3 WORDS, ALL CAPS, punchy dev slang ("WHY?!", "ONE CMD!", "IT WORKS!")
- ONE dominant visual per panel

TEXT RULES (CRITICAL):
- Speech bubbles: max 3 words, ALL CAPS only
- No descriptive text, labels, or paragraphs inside panels
- No caption, subtitle, or any text outside the panel borders
- No text below the image

SPECIFICITY:
- Panel 2: exact install command visible on terminal screen (pip install or npm install)
- Panel 3: 2-3 specific feature names from README as floating 3D cards
- All brackets filled from README — no placeholders

OUTPUT FORMAT (4 panels, 2×2 grid, wide 16:9):
Panel 1 – bold "THE STRUGGLE": [problem scene]. Slumped dev character, sweat. Dark red-grey. Speech: "[3 WORDS]".
Panel 2 – bold "THE INSTALL": Terminal with install command. Electric blue burst. Jaw-drop. Speech: "[3 WORDS]".
Panel 3 – bold "[FEATURE]": [feature working]. Floating cards: "[f1]", "[f2]". Purple-gold. Arms-spread awe.
Panel 4 – bold "THE WIN": [outcome]. Fist pump, confetti. Warm green. Speech: "[3 WORDS]". No text outside panels.

Negative prompt: photorealistic, anime, 2d flat, blurry, low quality, 5 panels, 6 panels, caption below image, subtitle.
"""


# ── System prompt builder ─────────────────────────────────────────────────────

_BASE_SYSTEM_PROMPT = """\
You write image generation prompts for Pixar-quality 3D comic strips — GitHub README hero images for developer tools.

Your job: read a project's context (title, description, README) and write a detailed, vivid
image generation prompt that will produce a stunning 4-panel comic strip banner.

## Step-by-step approach
1. Extract the CORE CONCEPT from the project context (what this tool does)
2. Invent a FUNNY SCENARIO where a developer struggles WITHOUT the tool
3. Show them discovering and installing it (with the exact install command)
4. Show the triumphant result with specific features from the README

SCENE VARIETY (pick ONE unique scenario — be creative, sarcastic, ironic):
- Dev crying over broken configs, YAML monsters attacking
- Dev drowning in a sea of error messages at 3am, energy drinks everywhere
- Dev presenting to investors, demo crashes live on stage
- Dev building a Rube Goldberg machine of microservices — tool replaces it all
- Dev stuck behind corporate firewall/NAT hell, VPN spinning forever
- Dev rage-quitting after the 9th timeout
Vary settings: server room, home office, rooftop terrace, conference stage, coffee shop, corporate lobby.
Use irony, sarcasm, absurd humor. Each banner should tell a DIFFERENT story.

{model_rules}

{comic_structure}

{style_section}

Write ONLY the prompt. 200-300 words. No placeholders, no preamble, no explanation, no markdown.
"""

_STYLE_SECTION_TEMPLATE = """\
## Visual style direction
The user has requested this aesthetic: {style_name}

Style description: {style_hint}

Use this as the primary aesthetic direction. Adapt it to suit the project's context —
do not copy it verbatim, but let it shape the mood, palette, and composition.
"""


def build_system_prompt(
    family: ImageModelFamily,
    style: BannerStyle | None = None,
) -> str:
    """Build a model-aware LLM system prompt for banner generation.

    Args:
        family: Image model family (determines prompt rules).
        style: Visual style enum — passed as aesthetic direction hint to the LLM.
               If None, LLM picks the style freely based on project context.
    """
    model_rules = _FAMILY_RULES[family]

    if style is not None:
        style_section = _STYLE_SECTION_TEMPLATE.format(
            style_name=style.value,
            style_hint=style.hint(),
        )
    else:
        style_section = (
            "## Visual style direction\n"
            "No specific style requested. Use Pixar/Disney 3D render as the default aesthetic. "
            "Friendly characters, studio three-point lighting, vivid saturated colors, "
            "subsurface scattering, exaggerated expressions."
        )

    return _BASE_SYSTEM_PROMPT.format(
        model_rules=model_rules,
        comic_structure=_COMIC_STRUCTURE,
        style_section=style_section,
    )


__all__ = ["build_system_prompt"]
