#!/usr/bin/env python3
"""
OurDigital Visual Storytelling Prompt Generator
Generates sophisticated image prompts for blog featured images
"""

import argparse
from typing import Dict, Tuple
import json

class VisualPromptGenerator:
    def __init__(self):
        self.style_base = (
            "sophisticated featured image, minimalist contemporary design, "
            "clean vector illustration with subtle texture overlays, "
            "1200x630px, suitable for blog header"
        )
        
        self.moods = {
            "contemplative": "contemplative and introspective atmosphere, zen-like calm",
            "critical": "analytical precision with underlying urgency, sharp clarity",
            "hopeful": "dawn breaking through uncertainty, warm optimism",
            "anxious": "subtle tension and uncertainty, digital unease",
            "philosophical": "deep meditation quality, timeless wisdom"
        }
        
        self.color_palettes = {
            "contemplative": "monochrome palette with single accent color",
            "critical": "cool blue-gray with sharp red accents",
            "hopeful": "warm amber gradients with sky blue highlights",
            "anxious": "desaturated colors with digital green touches",
            "philosophical": "near black and off-white with muted gold"
        }
        
        self.metaphor_types = {
            "technology": "organic-digital hybrid forms, natural systems becoming circuits",
            "identity": "layered masks, fragmented mirrors, dissolving boundaries",
            "network": "root systems, neural pathways, constellation patterns",
            "transformation": "metamorphosis states, particle dissolution, phase transitions",
            "knowledge": "light sources, growing trees, prismatic refractions"
        }

    def generate_prompt(
        self, 
        topic: str, 
        mood: str = "contemplative",
        metaphor: str = None,
        cultural_fusion: float = 0.6,
        abstract_level: float = 0.8
    ) -> str:
        """
        Generate a sophisticated image prompt for OurDigital blog
        
        Args:
            topic: Main subject of the blog post
            mood: Emotional tone (contemplative/critical/hopeful/anxious/philosophical)
            metaphor: Visual metaphor to use
            cultural_fusion: Balance of Korean-Western aesthetics (0-1)
            abstract_level: Level of abstraction (0=literal, 1=highly abstract)
        """
        
        # Build core prompt
        prompt_parts = [
            f"Create a {self.style_base} for blog post about {topic}.",
            ""
        ]
        
        # Add visual concept
        if metaphor:
            prompt_parts.append(f"Visual concept: {metaphor}.")
        else:
            prompt_parts.append(f"Visual concept: Abstract representation of {topic}.")
        
        prompt_parts.append("")
        
        # Add mood and atmosphere
        mood_desc = self.moods.get(mood, self.moods["contemplative"])
        prompt_parts.append(f"Atmosphere: {mood_desc}.")
        
        # Add color palette
        colors = self.color_palettes.get(mood, self.color_palettes["contemplative"])
        prompt_parts.append(f"Colors: {colors}.")
        
        # Add composition guidelines
        prompt_parts.extend([
            "",
            "Composition:",
            f"- {'Highly abstract' if abstract_level > 0.7 else 'Semi-abstract'} interpretation",
            f"- Minimum 20% negative space for contemplative breathing room",
            f"- Asymmetrical balance with {'strong' if abstract_level > 0.5 else 'subtle'} geometric structure"
        ])
        
        # Add cultural elements if needed
        if cultural_fusion > 0.3:
            fusion_level = "subtle" if cultural_fusion < 0.6 else "balanced"
            prompt_parts.append(
                f"- {fusion_level} integration of Korean minimalist aesthetics with Western modernism"
            )
        
        # Add quality notes
        prompt_parts.extend([
            "",
            "Technical notes:",
            "- Ensure clarity at thumbnail size (200px)",
            "- Avoid tech clichés (circuits, binary codes)",
            "- No stock photo aesthetics or literal interpretations",
            "- Timeless design that won't date quickly"
        ])
        
        # Add reference
        prompt_parts.extend([
            "",
            "Aesthetic reference: Combine Bauhaus principles with Agnes Martin's contemplative minimalism."
        ])
        
        return "\n".join(prompt_parts)

    def generate_variations(self, topic: str, count: int = 3) -> list:
        """Generate multiple prompt variations for the same topic"""
        variations = []
        moods = ["contemplative", "critical", "philosophical"]
        
        for i in range(min(count, len(moods))):
            prompt = self.generate_prompt(
                topic=topic,
                mood=moods[i],
                abstract_level=0.7 + (i * 0.1)
            )
            variations.append({
                "variation": i + 1,
                "mood": moods[i],
                "prompt": prompt
            })
        
        return variations

def main():
    parser = argparse.ArgumentParser(
        description="Generate visual prompts for OurDigital blog featured images"
    )
    parser.add_argument(
        "--topic", 
        required=True,
        help="Main topic/subject of the blog post"
    )
    parser.add_argument(
        "--mood",
        choices=["contemplative", "critical", "hopeful", "anxious", "philosophical"],
        default="contemplative",
        help="Emotional tone of the image"
    )
    parser.add_argument(
        "--metaphor",
        help="Specific visual metaphor to use"
    )
    parser.add_argument(
        "--cultural-fusion",
        type=float,
        default=0.6,
        help="Korean-Western aesthetic balance (0-1)"
    )
    parser.add_argument(
        "--abstract",
        type=float,
        default=0.8,
        help="Level of abstraction (0-1)"
    )
    parser.add_argument(
        "--variations",
        type=int,
        help="Generate N variations of the prompt"
    )
    parser.add_argument(
        "--json",
        action="store_true",
        help="Output as JSON"
    )
    
    args = parser.parse_args()
    
    generator = VisualPromptGenerator()
    
    if args.variations:
        results = generator.generate_variations(args.topic, args.variations)
        if args.json:
            print(json.dumps(results, indent=2, ensure_ascii=False))
        else:
            for var in results:
                print(f"\n--- Variation {var['variation']} ({var['mood']}) ---")
                print(var['prompt'])
    else:
        prompt = generator.generate_prompt(
            topic=args.topic,
            mood=args.mood,
            metaphor=args.metaphor,
            cultural_fusion=args.cultural_fusion,
            abstract_level=args.abstract
        )
        
        if args.json:
            result = {
                "topic": args.topic,
                "mood": args.mood,
                "prompt": prompt
            }
            print(json.dumps(result, indent=2, ensure_ascii=False))
        else:
            print(prompt)

if __name__ == "__main__":
    main()