"""
System module models - for global settings and prompts
"""
from django.db import models
from igny8_core.auth.models import AccountBaseModel

# Import settings models
from .settings_models import (
    SystemSettings, AccountSettings, UserSettings, ModuleSettings, AISettings
)


class AIPrompt(AccountBaseModel):
    """AI Prompt templates for various AI operations"""
    
    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'),
    ]
    
    prompt_type = models.CharField(max_length=50, choices=PROMPT_TYPE_CHOICES, db_index=True)
    prompt_value = models.TextField(help_text="The prompt template text")
    default_prompt = models.TextField(help_text="Default prompt value (for reset)")
    is_active = models.BooleanField(default=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'igny8_ai_prompts'
        ordering = ['prompt_type']
        unique_together = [['account', 'prompt_type']]  # Each account can have one prompt per type
        indexes = [
            models.Index(fields=['prompt_type']),
            models.Index(fields=['account', 'prompt_type']),
        ]
    
    def __str__(self):
        return f"{self.get_prompt_type_display()}"


class IntegrationSettings(AccountBaseModel):
    """Integration settings for OpenAI, Runware, GSC, etc."""
    
    INTEGRATION_TYPE_CHOICES = [
        ('openai', 'OpenAI'),
        ('runware', 'Runware'),
        ('gsc', 'Google Search Console'),
        ('image_generation', 'Image Generation Service'),
    ]
    
    integration_type = models.CharField(max_length=50, choices=INTEGRATION_TYPE_CHOICES, db_index=True)
    config = models.JSONField(default=dict, help_text="Integration configuration (API keys, settings, etc.)")
    is_active = models.BooleanField(default=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'igny8_integration_settings'
        unique_together = [['account', 'integration_type']]
        ordering = ['integration_type']
        indexes = [
            models.Index(fields=['integration_type']),
            models.Index(fields=['account', 'integration_type']),
        ]
    
    def __str__(self):
        account = getattr(self, 'account', None)
        return f"{self.get_integration_type_display()} - {account.name if account else 'No Account'}"


class AuthorProfile(AccountBaseModel):
    """
    Writing style profiles - tone, language, structure templates.
    Examples: "SaaS B2B Informative", "E-commerce Product Descriptions", etc.
    """
    name = models.CharField(max_length=255, help_text="Profile name (e.g., 'SaaS B2B Informative')")
    description = models.TextField(blank=True, help_text="Description of the writing style")
    tone = models.CharField(
        max_length=100,
        help_text="Writing tone (e.g., 'Professional', 'Casual', 'Technical', 'Conversational')"
    )
    language = models.CharField(max_length=50, default='en', help_text="Language code (e.g., 'en', 'es', 'fr')")
    structure_template = models.JSONField(
        default=dict,
        help_text="Structure template defining content sections and their order"
    )
    is_active = models.BooleanField(default=True, db_index=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'igny8_author_profiles'
        ordering = ['name']
        verbose_name = 'Author Profile'
        verbose_name_plural = 'Author Profiles'
        indexes = [
            models.Index(fields=['account', 'is_active']),
            models.Index(fields=['name']),
        ]
    
    def __str__(self):
        account = getattr(self, 'account', None)
        return f"{self.name} ({account.name if account else 'No Account'})"


class Strategy(AccountBaseModel):
    """
    Defined content strategies per sector, integrating prompt types, section logic, etc.
    Links together prompts, author profiles, and sector-specific content strategies.
    """
    name = models.CharField(max_length=255, help_text="Strategy name")
    description = models.TextField(blank=True, help_text="Description of the content strategy")
    sector = models.ForeignKey(
        'igny8_core_auth.Sector',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='strategies',
        help_text="Optional: Link strategy to a specific sector"
    )
    prompt_types = models.JSONField(
        default=list,
        help_text="List of prompt types to use (e.g., ['clustering', 'ideas', 'content_generation'])"
    )
    section_logic = models.JSONField(
        default=dict,
        help_text="Section logic configuration defining content structure and flow"
    )
    is_active = models.BooleanField(default=True, db_index=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'igny8_strategies'
        ordering = ['name']
        verbose_name = 'Strategy'
        verbose_name_plural = 'Strategies'
        indexes = [
            models.Index(fields=['account', 'is_active']),
            models.Index(fields=['account', 'sector']),
            models.Index(fields=['name']),
        ]
    
    def __str__(self):
        sector_name = self.sector.name if self.sector else 'Global'
        return f"{self.name} ({sector_name})"
