"""
CODH Projects Models
Project DNA Collection and Management
"""

import uuid
from django.db import models
from django.conf import settings


class Project(models.Model):
    """
    Main project model
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='projects')
    
    # Basic Info
    name = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    
    # Project Type
    TYPE_CHOICES = [
        ('website', 'Website'),
        ('web_app', 'Web Application'),
        ('mobile_app', 'Mobile Application'),
        ('ecommerce', 'E-Commerce'),
        ('saas', 'SaaS Platform'),
        ('api', 'API Service'),
        ('other', 'Other'),
    ]
    project_type = models.CharField(max_length=20, choices=TYPE_CHOICES, default='website')
    
    # Status
    STATUS_CHOICES = [
        ('draft', 'Draft'),
        ('pending_analysis', 'Pending AI Analysis'),
        ('analyzed', 'Analyzed'),
        ('pending_approval', 'Pending Approval'),
        ('approved', 'Approved'),
        ('in_progress', 'In Progress'),
        ('completed', 'Completed'),
        ('cancelled', 'Cancelled'),
        ('on_hold', 'On Hold'),
    ]
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft')
    
    # Priority
    PRIORITY_CHOICES = [
        ('low', 'Low'),
        ('medium', 'Medium'),
        ('high', 'High'),
        ('urgent', 'Urgent'),
    ]
    priority = models.CharField(max_length=10, choices=PRIORITY_CHOICES, default='medium')
    
    # Timeline
    start_date = models.DateField(null=True, blank=True)
    target_date = models.DateField(null=True, blank=True)
    completed_date = models.DateField(null=True, blank=True)
    
    # Budget
    estimated_budget = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True)
    final_budget = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True)
    
    # Related objects
    hosting_account = models.ForeignKey('hosting.HostingAccount', on_delete=models.SET_NULL, null=True, blank=True, related_name='projects')
    subscription = models.ForeignKey('subscriptions.Subscription', on_delete=models.SET_NULL, null=True, blank=True, related_name='projects')
    
    # WordPress Integration
    wordpress_site = models.ForeignKey('wordpress.WordPressSite', on_delete=models.SET_NULL, null=True, blank=True, related_name='projects')
    
    # AI Analysis
    ai_report = models.OneToOneField('ai_engine.AIReport', on_delete=models.SET_NULL, null=True, blank=True, related_name='project')
    
    # Metadata
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'Project'
        verbose_name_plural = 'Projects'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', 'status']),
            models.Index(fields=['project_type']),
            models.Index(fields=['created_at']),
        ]
    
    def __str__(self):
        return f"{self.name} ({self.get_status_display()})"


class ProjectDNA(models.Model):
    """
    Project DNA - Detailed project requirements and specifications
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    
    project = models.OneToOneField(Project, on_delete=models.CASCADE, related_name='dna')
    
    # Business Information
    business_name = models.CharField(max_length=255, blank=True)
    industry = models.CharField(max_length=100, blank=True)
    target_audience = models.TextField(blank=True)
    business_goals = models.JSONField(default=list, blank=True)
    
    # Design Requirements
    design_style = models.CharField(max_length=100, blank=True)
    color_preferences = models.JSONField(default=list, blank=True)
    logo_available = models.BooleanField(default=False)
    branding_guidelines = models.BooleanField(default=False)
    
    # Functionality
    required_features = models.JSONField(default=list, blank=True)
    integrations_needed = models.JSONField(default=list, blank=True)
    user_authentication = models.BooleanField(default=False)
    payment_processing = models.BooleanField(default=False)
    
    # Content
    content_provided = models.BooleanField(default=False)
    content_type = models.CharField(max_length=100, blank=True)
    images_provided = models.BooleanField(default=False)
    copywriting_needed = models.BooleanField(default=False)
    
    # Technical
    preferred_platform = models.CharField(max_length=100, blank=True)
    hosting_preference = models.CharField(max_length=100, blank=True)
    domain_status = models.CharField(max_length=100, blank=True)
    ssl_required = models.BooleanField(default=True)
    
    # SEO & Marketing
    seo_needed = models.BooleanField(default=False)
    analytics_needed = models.BooleanField(default=False)
    social_media_integration = models.BooleanField(default=False)
    
    # Additional
    competitor_websites = models.JSONField(default=list, blank=True)
    reference_websites = models.JSONField(default=list, blank=True)
    special_requirements = models.TextField(blank=True)
    
    # AI Scores
    complexity_score = models.IntegerField(default=0)  # 0-100
    clarity_score = models.IntegerField(default=0)  # 0-100
    completeness_score = models.IntegerField(default=0)  # 0-100
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'Project DNA'
        verbose_name_plural = 'Project DNA Records'


class ProjectFile(models.Model):
    """
    Files attached to projects
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='files')
    
    name = models.CharField(max_length=255)
    file = models.FileField(upload_to='project_files/')
    file_type = models.CharField(max_length=50, blank=True)
    file_size = models.IntegerField(default=0)  # in bytes
    
    description = models.TextField(blank=True)
    
    uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        verbose_name = 'Project File'
        verbose_name_plural = 'Project Files'
        ordering = ['-uploaded_at']


class ProjectNote(models.Model):
    """
    Notes and comments on projects
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='notes')
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    
    content = models.TextField()
    
    # For threaded comments
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='replies')
    
    is_internal = models.BooleanField(default=False)  # Internal notes not visible to clients
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'Project Note'
        verbose_name_plural = 'Project Notes'
        ordering = ['-created_at']


class ProjectMilestone(models.Model):
    """
    Project milestones and deliverables
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='milestones')
    
    name = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    
    due_date = models.DateField()
    completed_date = models.DateField(null=True, blank=True)
    
    STATUS_CHOICES = [
        ('pending', 'Pending'),
        ('in_progress', 'In Progress'),
        ('completed', 'Completed'),
        ('overdue', 'Overdue'),
    ]
    status = models.CharField(max_length=15, choices=STATUS_CHOICES, default='pending')
    
    deliverables = models.JSONField(default=list, blank=True)
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'Project Milestone'
        verbose_name_plural = 'Project Milestones'
        ordering = ['due_date']


class ProjectTask(models.Model):
    """
    Tasks within projects
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='tasks')
    milestone = models.ForeignKey(ProjectMilestone, on_delete=models.SET_NULL, null=True, blank=True, related_name='tasks')
    
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    
    assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name='assigned_tasks')
    
    STATUS_CHOICES = [
        ('todo', 'To Do'),
        ('in_progress', 'In Progress'),
        ('review', 'In Review'),
        ('completed', 'Completed'),
    ]
    status = models.CharField(max_length=15, choices=STATUS_CHOICES, default='todo')
    
    PRIORITY_CHOICES = [
        ('low', 'Low'),
        ('medium', 'Medium'),
        ('high', 'High'),
    ]
    priority = models.CharField(max_length=10, choices=PRIORITY_CHOICES, default='medium')
    
    estimated_hours = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True)
    actual_hours = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True)
    
    due_date = models.DateField(null=True, blank=True)
    completed_at = models.DateTimeField(null=True, blank=True)
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'Project Task'
        verbose_name_plural = 'Project Tasks'
        ordering = ['-priority', 'due_date']
