#!/usr/bin/env python3
"""
OurDigital Mood Calibrator
Fine-tune emotional and stylistic parameters for visual prompts
"""

import json
from typing import Dict, Any
import argparse

class MoodCalibrator:
    def __init__(self):
        self.presets = {
            "default": {
                "contemplative_depth": 0.8,
                "cultural_fusion": 0.6,
                "technical_precision": 0.7,
                "emotional_weight": 0.5,
                "innovation_index": 0.7
            },
            "philosophical_essay": {
                "contemplative_depth": 0.95,
                "cultural_fusion": 0.7,
                "technical_precision": 0.6,
                "emotional_weight": 0.3,
                "innovation_index": 0.8
            },
            "technical_analysis": {
                "contemplative_depth": 0.6,
                "cultural_fusion": 0.4,
                "technical_precision": 0.9,
                "emotional_weight": 0.3,
                "innovation_index": 0.6
            },
            "social_commentary": {
                "contemplative_depth": 0.7,
                "cultural_fusion": 0.6,
                "technical_precision": 0.5,
                "emotional_weight": 0.7,
                "innovation_index": 0.7
            },
            "cultural_exploration": {
                "contemplative_depth": 0.8,
                "cultural_fusion": 0.9,
                "technical_precision": 0.4,
                "emotional_weight": 0.6,
                "innovation_index": 0.8
            }
        }
        
        self.parameter_descriptions = {
            "contemplative_depth": "Level of abstraction (0=literal, 1=highly abstract)",
            "cultural_fusion": "Balance of Korean-Western aesthetics (0=Western only, 1=Korean dominant)",
            "technical_precision": "Clean geometric vs organic forms (0=organic, 1=geometric)",
            "emotional_weight": "Mood intensity (0=neutral, 1=heavy atmosphere)",
            "innovation_index": "Traditional vs experimental approach (0=traditional, 1=experimental)"
        }

    def calibrate(self, preset: str = "default", **overrides) -> Dict[str, float]:
        """
        Get calibrated mood parameters
        
        Args:
            preset: Base preset to use
            **overrides: Specific parameter overrides
        
        Returns:
            Dictionary of calibrated parameters
        """
        params = self.presets.get(preset, self.presets["default"]).copy()
        
        # Apply overrides
        for key, value in overrides.items():
            if key in params:
                params[key] = max(0, min(1, value))  # Clamp to 0-1
        
        return params

    def generate_modifier_text(self, params: Dict[str, float]) -> str:
        """
        Generate text modifiers based on parameters
        
        Args:
            params: Dictionary of mood parameters
        
        Returns:
            Text description for prompt modification
        """
        modifiers = []
        
        # Contemplative depth
        if params["contemplative_depth"] > 0.8:
            modifiers.append("highly abstract and philosophical")
        elif params["contemplative_depth"] > 0.6:
            modifiers.append("semi-abstract with symbolic elements")
        else:
            modifiers.append("grounded with recognizable forms")
        
        # Cultural fusion
        if params["cultural_fusion"] > 0.7:
            modifiers.append("strong Korean aesthetic influence")
        elif params["cultural_fusion"] > 0.4:
            modifiers.append("balanced East-West aesthetic fusion")
        else:
            modifiers.append("Western minimalist approach")
        
        # Technical precision
        if params["technical_precision"] > 0.7:
            modifiers.append("precise geometric construction")
        elif params["technical_precision"] > 0.4:
            modifiers.append("blend of geometric and organic")
        else:
            modifiers.append("flowing organic forms")
        
        # Emotional weight
        if params["emotional_weight"] > 0.7:
            modifiers.append("heavy, contemplative atmosphere")
        elif params["emotional_weight"] > 0.4:
            modifiers.append("balanced emotional tone")
        else:
            modifiers.append("light, open feeling")
        
        # Innovation index
        if params["innovation_index"] > 0.7:
            modifiers.append("experimental and avant-garde")
        elif params["innovation_index"] > 0.4:
            modifiers.append("contemporary with classic elements")
        else:
            modifiers.append("timeless and traditional")
        
        return ", ".join(modifiers)

    def suggest_color_temperature(self, params: Dict[str, float]) -> str:
        """
        Suggest color temperature based on parameters
        
        Args:
            params: Dictionary of mood parameters
        
        Returns:
            Color temperature suggestion
        """
        emotional = params.get("emotional_weight", 0.5)
        technical = params.get("technical_precision", 0.7)
        
        if emotional > 0.6:
            if technical > 0.6:
                return "Cool palette with strategic warm accents"
            else:
                return "Warm, earthy tones with depth"
        else:
            if technical > 0.6:
                return "Neutral grays with single accent color"
            else:
                return "Soft, desaturated natural colors"

    def export_for_prompt(self, params: Dict[str, float]) -> Dict[str, Any]:
        """
        Export parameters in a format ready for prompt generation
        
        Args:
            params: Dictionary of mood parameters
        
        Returns:
            Formatted export for prompt generation
        """
        return {
            "parameters": params,
            "modifiers": self.generate_modifier_text(params),
            "color_temperature": self.suggest_color_temperature(params),
            "abstraction_level": params["contemplative_depth"],
            "cultural_balance": params["cultural_fusion"]
        }

def main():
    parser = argparse.ArgumentParser(
        description="Calibrate mood parameters for OurDigital visual prompts"
    )
    parser.add_argument(
        "--preset",
        choices=["default", "philosophical_essay", "technical_analysis", 
                 "social_commentary", "cultural_exploration"],
        default="default",
        help="Base preset to use"
    )
    parser.add_argument(
        "--contemplative-depth",
        type=float,
        help="Override contemplative depth (0-1)"
    )
    parser.add_argument(
        "--cultural-fusion",
        type=float,
        help="Override cultural fusion (0-1)"
    )
    parser.add_argument(
        "--technical-precision",
        type=float,
        help="Override technical precision (0-1)"
    )
    parser.add_argument(
        "--emotional-weight",
        type=float,
        help="Override emotional weight (0-1)"
    )
    parser.add_argument(
        "--innovation-index",
        type=float,
        help="Override innovation index (0-1)"
    )
    parser.add_argument(
        "--export",
        action="store_true",
        help="Export full configuration for prompt generation"
    )
    
    args = parser.parse_args()
    
    calibrator = MoodCalibrator()
    
    # Build overrides
    overrides = {}
    if args.contemplative_depth is not None:
        overrides["contemplative_depth"] = args.contemplative_depth
    if args.cultural_fusion is not None:
        overrides["cultural_fusion"] = args.cultural_fusion
    if args.technical_precision is not None:
        overrides["technical_precision"] = args.technical_precision
    if args.emotional_weight is not None:
        overrides["emotional_weight"] = args.emotional_weight
    if args.innovation_index is not None:
        overrides["innovation_index"] = args.innovation_index
    
    # Calibrate
    params = calibrator.calibrate(args.preset, **overrides)
    
    if args.export:
        export = calibrator.export_for_prompt(params)
        print(json.dumps(export, indent=2, ensure_ascii=False))
    else:
        print(f"Calibrated Parameters for '{args.preset}':")
        print("-" * 50)
        for key, value in params.items():
            desc = calibrator.parameter_descriptions[key]
            print(f"{key}: {value:.2f} - {desc}")
        print("-" * 50)
        print(f"Modifiers: {calibrator.generate_modifier_text(params)}")
        print(f"Color Temperature: {calibrator.suggest_color_temperature(params)}")

if __name__ == "__main__":
    main()