"""
Settings Models for System, Account, User, Module, and AI Settings
"""
from django.db import models
from igny8_core.auth.models import AccountBaseModel


class BaseSettings(AccountBaseModel):
    """Base class for all account-scoped settings models"""
    config = models.JSONField(default=dict, help_text="Settings configuration as JSON")
    is_active = models.BooleanField(default=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        abstract = True


class SystemSettings(models.Model):
    """Global system-wide settings (no account scope)"""
    key = models.CharField(max_length=255, unique=True, db_index=True, help_text="Settings key identifier")
    value = models.JSONField(default=dict, help_text="Settings value as JSON")
    description = models.TextField(blank=True, help_text="Description of this setting")
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'igny8_system_settings'
        ordering = ['key']
        indexes = [
            models.Index(fields=['key']),
        ]
    
    def __str__(self):
        return f"SystemSetting: {self.key}"


class AccountSettings(BaseSettings):
    """Account-level settings"""
    key = models.CharField(max_length=255, db_index=True, help_text="Settings key identifier")
    
    class Meta:
        db_table = 'igny8_account_settings'
        unique_together = [['account', 'key']]
        indexes = [
            models.Index(fields=['account', 'key']),
        ]
        ordering = ['key']
    
    def __str__(self):
        account = getattr(self, 'account', None)
        return f"AccountSetting: {account.name if account else 'No Account'} - {self.key}"


class UserSettings(models.Model):
    """User-level settings"""
    user = models.ForeignKey('igny8_core_auth.User', on_delete=models.CASCADE, related_name='user_settings')
    account = models.ForeignKey('igny8_core_auth.Account', on_delete=models.CASCADE, related_name='user_settings', db_column='tenant_id')
    key = models.CharField(max_length=255, db_index=True, help_text="Settings key identifier")
    value = models.JSONField(default=dict, help_text="Settings value as JSON")
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'igny8_user_settings'
        unique_together = [['user', 'account', 'key']]
        indexes = [
            models.Index(fields=['user', 'account', 'key']),
            models.Index(fields=['account', 'key']),
        ]
        ordering = ['key']
    
    def __str__(self):
        return f"UserSetting: {self.user.email} - {self.key}"


class ModuleSettings(BaseSettings):
    """Module-specific settings"""
    module_name = models.CharField(max_length=100, db_index=True, help_text="Module name (e.g., 'planner', 'writer')")
    key = models.CharField(max_length=255, db_index=True, help_text="Settings key identifier")
    
    class Meta:
        db_table = 'igny8_module_settings'
        unique_together = [['account', 'module_name', 'key']]
        indexes = [
            models.Index(fields=['account', 'module_name', 'key']),
            models.Index(fields=['module_name', 'key']),
        ]
        ordering = ['module_name', 'key']
    
    def __str__(self):
        return f"ModuleSetting: {self.module_name} - {self.key}"


class ModuleEnableSettings(AccountBaseModel):
    """Module enable/disable settings per account"""
    planner_enabled = models.BooleanField(default=True, help_text="Enable Planner module")
    writer_enabled = models.BooleanField(default=True, help_text="Enable Writer module")
    thinker_enabled = models.BooleanField(default=True, help_text="Enable Thinker module")
    automation_enabled = models.BooleanField(default=True, help_text="Enable Automation module")
    site_builder_enabled = models.BooleanField(default=True, help_text="Enable Site Builder module")
    linker_enabled = models.BooleanField(default=True, help_text="Enable Linker module")
    optimizer_enabled = models.BooleanField(default=True, help_text="Enable Optimizer module")
    publisher_enabled = models.BooleanField(default=True, help_text="Enable Publisher module")
    
    class Meta:
        db_table = 'igny8_module_enable_settings'
        unique_together = [['account']]  # One record per account
    
    def __str__(self):
        account = getattr(self, 'account', None)
        return f"ModuleEnableSettings: {account.name if account else 'No Account'}"
    
    @classmethod
    def get_or_create_for_account(cls, account):
        """Get or create module enable settings for an account"""
        settings, created = cls.objects.get_or_create(account=account)
        return settings
    
    def is_module_enabled(self, module_name):
        """Check if a module is enabled"""
        mapping = {
            'planner': self.planner_enabled,
            'writer': self.writer_enabled,
            'thinker': self.thinker_enabled,
            'automation': self.automation_enabled,
            'site_builder': self.site_builder_enabled,
            'linker': self.linker_enabled,
            'optimizer': self.optimizer_enabled,
            'publisher': self.publisher_enabled,
        }
        return mapping.get(module_name, True)  # Default to enabled if unknown


# AISettings extends IntegrationSettings (which already exists)
# We'll create it as a separate model that can reference IntegrationSettings
class AISettings(AccountBaseModel):
    """AI-specific settings extending IntegrationSettings pattern"""
    integration_type = models.CharField(
        max_length=50,
        db_index=True,
        help_text="Integration type (e.g., 'openai', 'runware')"
    )
    config = models.JSONField(
        default=dict,
        help_text="Integration configuration (API keys, settings, etc.)"
    )
    model_preferences = models.JSONField(
        default=dict,
        help_text="Model preferences per operation type"
    )
    cost_limits = models.JSONField(
        default=dict,
        help_text="Cost limits and budgets"
    )
    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_settings'
        unique_together = [['account', 'integration_type']]
        indexes = [
            models.Index(fields=['integration_type']),
            models.Index(fields=['account', 'integration_type']),
        ]
        ordering = ['integration_type']
    
    def __str__(self):
        account = getattr(self, 'account', None)
        account_name = account.name if account else 'No Account'
        return f"AISettings: {self.integration_type} - {account_name}"

