"""
Global settings models - Platform-wide defaults
These models store system-wide defaults that all accounts use.
Accounts can override model selection and parameters (but NOT API keys).
"""
from django.db import models
from django.conf import settings


class GlobalIntegrationSettings(models.Model):
    """
    Platform-wide API keys and default integration settings.
    Singleton pattern - only ONE instance exists (pk=1).
    
    IMPORTANT:
    - API keys stored here are used by ALL accounts (no exceptions)
    - Model selections and parameters are defaults
    - Accounts can override model/params via IntegrationSettings model
    - Free plan: Cannot override, must use these defaults
    - Starter/Growth/Scale: Can override model, temperature, tokens, etc.
    """
    
    OPENAI_MODEL_CHOICES = [
        ('gpt-4.1', 'GPT-4.1 - $2.00 / $8.00 per 1M tokens'),
        ('gpt-4o-mini', 'GPT-4o mini - $0.15 / $0.60 per 1M tokens'),
        ('gpt-4o', 'GPT-4o - $2.50 / $10.00 per 1M tokens'),
        ('gpt-4-turbo-preview', 'GPT-4 Turbo Preview - $10.00 / $30.00 per 1M tokens'),
        ('gpt-5.1', 'GPT-5.1 - $1.25 / $10.00 per 1M tokens (16K)'),
        ('gpt-5.2', 'GPT-5.2 - $1.75 / $14.00 per 1M tokens (16K)'),
    ]
    
    DALLE_MODEL_CHOICES = [
        ('dall-e-3', 'DALL·E 3 - $0.040 per image'),
        ('dall-e-2', 'DALL·E 2 - $0.020 per image'),
    ]
    
    DALLE_SIZE_CHOICES = [
        ('1024x1024', '1024x1024 (Square)'),
        ('1792x1024', '1792x1024 (Landscape)'),
        ('1024x1792', '1024x1792 (Portrait)'),
        ('512x512', '512x512 (Small Square)'),
    ]
    
    DALLE_QUALITY_CHOICES = [
        ('standard', 'Standard'),
        ('hd', 'HD'),
    ]
    
    DALLE_STYLE_CHOICES = [
        ('vivid', 'Vivid'),
        ('natural', 'Natural'),
    ]
    
    RUNWARE_MODEL_CHOICES = [
        ('runware:97@1', 'Runware 97@1 - Versatile Model'),
        ('runware:100@1', 'Runware 100@1 - High Quality'),
        ('runware:101@1', 'Runware 101@1 - Fast Generation'),
    ]
    
    IMAGE_QUALITY_CHOICES = [
        ('standard', 'Standard'),
        ('hd', 'HD'),
    ]
    
    IMAGE_STYLE_CHOICES = [
        ('vivid', 'Vivid'),
        ('natural', 'Natural'),
        ('realistic', 'Realistic'),
        ('artistic', 'Artistic'),
        ('cartoon', 'Cartoon'),
    ]
    
    IMAGE_SERVICE_CHOICES = [
        ('openai', 'OpenAI DALL-E'),
        ('runware', 'Runware'),
    ]
    
    # OpenAI Settings (for text generation)
    openai_api_key = models.CharField(
        max_length=500,
        blank=True,
        help_text="Platform OpenAI API key - used by ALL accounts"
    )
    openai_model = models.CharField(
        max_length=100,
        default='gpt-4o-mini',
        choices=OPENAI_MODEL_CHOICES,
        help_text="Default text generation model (accounts can override if plan allows)"
    )
    openai_temperature = models.FloatField(
        default=0.7,
        help_text="Default temperature 0.0-2.0 (accounts can override if plan allows)"
    )
    openai_max_tokens = models.IntegerField(
        default=8192,
        help_text="Default max tokens for responses (accounts can override if plan allows)"
    )
    
    # Image Generation Settings (OpenAI/DALL-E)
    dalle_api_key = models.CharField(
        max_length=500,
        blank=True,
        help_text="Platform DALL-E API key - used by ALL accounts (can be same as OpenAI)"
    )
    dalle_model = models.CharField(
        max_length=100,
        default='dall-e-3',
        choices=DALLE_MODEL_CHOICES,
        help_text="Default DALL-E model (accounts can override if plan allows)"
    )
    dalle_size = models.CharField(
        max_length=20,
        default='1024x1024',
        choices=DALLE_SIZE_CHOICES,
        help_text="Default image size (accounts can override if plan allows)"
    )
    
    # Image Generation Settings (Runware)
    runware_api_key = models.CharField(
        max_length=500,
        blank=True,
        help_text="Platform Runware API key - used by ALL accounts"
    )
    runware_model = models.CharField(
        max_length=100,
        default='runware:97@1',
        choices=RUNWARE_MODEL_CHOICES,
        help_text="Default Runware model (accounts can override if plan allows)"
    )
    
    # Default Image Generation Service
    default_image_service = models.CharField(
        max_length=20,
        default='openai',
        choices=IMAGE_SERVICE_CHOICES,
        help_text="Default image generation service for all accounts (openai=DALL-E, runware=Runware)"
    )
    
    # Universal Image Generation Settings (applies to ALL providers)
    image_quality = models.CharField(
        max_length=20,
        default='standard',
        choices=IMAGE_QUALITY_CHOICES,
        help_text="Default image quality for all providers (accounts can override if plan allows)"
    )
    image_style = models.CharField(
        max_length=20,
        default='realistic',
        choices=IMAGE_STYLE_CHOICES,
        help_text="Default image style for all providers (accounts can override if plan allows)"
    )
    max_in_article_images = models.IntegerField(
        default=2,
        help_text="Default maximum images to generate per article (1-5, accounts can override if plan allows)"
    )
    desktop_image_size = models.CharField(
        max_length=20,
        default='1024x1024',
        help_text="Default desktop image size (accounts can override if plan allows)"
    )
    mobile_image_size = models.CharField(
        max_length=20,
        default='512x512',
        help_text="Default mobile image size (accounts can override if plan allows)"
    )
    
    # Metadata
    is_active = models.BooleanField(default=True)
    last_updated = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='global_settings_updates'
    )
    
    class Meta:
        db_table = 'igny8_global_integration_settings'
        verbose_name = "Global Integration Settings"
        verbose_name_plural = "Global Integration Settings"
    
    def save(self, *args, **kwargs):
        # Enforce singleton - always use pk=1
        self.pk = 1
        super().save(*args, **kwargs)
    
    @classmethod
    def get_instance(cls):
        """Get or create the singleton instance"""
        obj, created = cls.objects.get_or_create(pk=1)
        return obj
    
    def __str__(self):
        return "Global Integration Settings"




class GlobalAIPrompt(models.Model):
    """
    Platform-wide default AI prompt templates.
    All accounts use these by default. Accounts can save overrides which are stored
    in the AIPrompt model with the default_prompt field preserving this global value.
    """
    
    PROMPT_TYPE_CHOICES = [
        ('clustering', 'Clustering'),
        ('ideas', 'Ideas Generation'),
        ('content_generation', 'Content Generation'),
        ('image_prompt_extraction', 'Image Prompt Extraction'),
        ('image_prompt_template', 'Image Prompt Template'),
        ('negative_prompt', 'Negative Prompt'),
        ('site_structure_generation', 'Site Structure Generation'),
        ('product_generation', 'Product Content Generation'),
        ('service_generation', 'Service Page Generation'),
        ('taxonomy_generation', 'Taxonomy Generation'),
    ]
    
    prompt_type = models.CharField(
        max_length=50,
        choices=PROMPT_TYPE_CHOICES,
        unique=True,
        help_text="Type of AI operation this prompt is for"
    )
    prompt_value = models.TextField(help_text="Default prompt template")
    description = models.TextField(blank=True, help_text="Description of what this prompt does")
    variables = models.JSONField(
        default=list,
        blank=True,
        help_text="Optional: List of variables used in the prompt (e.g., {keyword}, {industry})"
    )
    is_active = models.BooleanField(default=True, db_index=True)
    version = models.IntegerField(default=1, help_text="Prompt version for tracking changes")
    last_updated = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'igny8_global_ai_prompts'
        verbose_name = "Global AI Prompt"
        verbose_name_plural = "Global AI Prompts"
        ordering = ['prompt_type']
    
    def __str__(self):
        return f"{self.get_prompt_type_display()} (v{self.version})"


class GlobalAuthorProfile(models.Model):
    """
    Platform-wide author persona templates.
    All accounts can clone these profiles and customize them.
    """
    
    CATEGORY_CHOICES = [
        ('saas', 'SaaS/B2B'),
        ('ecommerce', 'E-commerce'),
        ('blog', 'Blog/Publishing'),
        ('technical', 'Technical'),
        ('creative', 'Creative'),
        ('news', 'News/Media'),
        ('academic', 'Academic'),
    ]
    
    name = models.CharField(
        max_length=255,
        unique=True,
        help_text="Profile name (e.g., 'SaaS B2B Professional')"
    )
    description = models.TextField(help_text="Description of the writing style")
    tone = models.CharField(
        max_length=100,
        help_text="Writing tone (e.g., 'Professional', 'Casual', 'Technical')"
    )
    language = models.CharField(
        max_length=50,
        default='en',
        help_text="Language code"
    )
    structure_template = models.JSONField(
        default=dict,
        help_text="Structure template defining content sections"
    )
    category = models.CharField(
        max_length=50,
        choices=CATEGORY_CHOICES,
        help_text="Profile category"
    )
    is_active = models.BooleanField(default=True, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        db_table = 'igny8_global_author_profiles'
        verbose_name = "Global Author Profile"
        verbose_name_plural = "Global Author Profiles"
        ordering = ['category', 'name']
    
    def __str__(self):
        return f"{self.name} ({self.get_category_display()})"


class GlobalStrategy(models.Model):
    """
    Platform-wide content strategy templates.
    All accounts can clone these strategies and customize them.
    """
    
    CATEGORY_CHOICES = [
        ('blog', 'Blog Content'),
        ('ecommerce', 'E-commerce'),
        ('saas', 'SaaS/B2B'),
        ('news', 'News/Media'),
        ('technical', 'Technical Documentation'),
        ('marketing', 'Marketing Content'),
    ]
    
    name = models.CharField(
        max_length=255,
        unique=True,
        help_text="Strategy name"
    )
    description = models.TextField(help_text="Description of the content strategy")
    prompt_types = models.JSONField(
        default=list,
        help_text="List of prompt types to use"
    )
    section_logic = models.JSONField(
        default=dict,
        help_text="Section logic configuration"
    )
    category = models.CharField(
        max_length=50,
        choices=CATEGORY_CHOICES,
        help_text="Strategy category"
    )
    is_active = models.BooleanField(default=True, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        db_table = 'igny8_global_strategies'
        verbose_name = "Global Strategy"
        verbose_name_plural = "Global Strategies"
        ordering = ['category', 'name']
    
    def __str__(self):
        return f"{self.name} ({self.get_category_display()})"


class GlobalModuleSettings(models.Model):
    """
    Global module enable/disable settings (platform-wide).
    Singleton model - only one record exists (pk=1).
    Controls which modules are available across the entire platform.
    No per-account overrides allowed - this is admin-only control.
    """
    planner_enabled = models.BooleanField(
        default=True,
        help_text="Enable Planner module platform-wide"
    )
    writer_enabled = models.BooleanField(
        default=True,
        help_text="Enable Writer module platform-wide"
    )
    thinker_enabled = models.BooleanField(
        default=True,
        help_text="Enable Thinker module platform-wide"
    )
    automation_enabled = models.BooleanField(
        default=True,
        help_text="Enable Automation module platform-wide"
    )
    site_builder_enabled = models.BooleanField(
        default=True,
        help_text="Enable Site Builder module platform-wide"
    )
    linker_enabled = models.BooleanField(
        default=True,
        help_text="Enable Linker module platform-wide"
    )
    optimizer_enabled = models.BooleanField(
        default=True,
        help_text="Enable Optimizer module platform-wide"
    )
    publisher_enabled = models.BooleanField(
        default=True,
        help_text="Enable Publisher module platform-wide"
    )
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'igny8_global_module_settings'
        verbose_name = 'Global Module Settings'
        verbose_name_plural = 'Global Module Settings'
    
    def __str__(self):
        return "Global Module Settings"
    
    def save(self, *args, **kwargs):
        """Enforce singleton pattern"""
        self.pk = 1
        super().save(*args, **kwargs)
    
    def delete(self, *args, **kwargs):
        """Prevent deletion"""
        pass
    
    @classmethod
    def get_instance(cls):
        """Get or create the singleton instance"""
        obj, created = cls.objects.get_or_create(pk=1)
        return obj
    
    def is_module_enabled(self, module_name: str) -> bool:
        """Check if a module is enabled"""
        field_name = f"{module_name}_enabled"
        return getattr(self, field_name, False)
