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


class CostSheet(models.Model):
    """
    The costing calculator for a lead — tracks team allocation,
    tools, overhead, contingency, and profit margin.
    """
    STATUS_CHOICES = [
        ('Draft', 'Draft'),
        ('Submitted', 'Submitted for Approval'),
        ('Under_Review', 'Under Review'),
        ('Approved', 'Approved'),
        ('Rejected', 'Rejected'),
        ('Revised', 'Needs Revision'),
    ]

    lead = models.ForeignKey('leads.Lead', on_delete=models.CASCADE, related_name='cost_sheets')
    version = models.PositiveIntegerField(default=1)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='Draft')

    # Auto-calculated totals
    hr_cost = models.DecimalField(max_digits=14, decimal_places=2, default=0)
    tools_cost = models.DecimalField(max_digits=14, decimal_places=2, default=0)

    # Overhead
    overhead_type = models.CharField(
        max_length=10,
        choices=[('percent', 'Percentage'), ('fixed', 'Fixed Amount')],
        default='percent'
    )
    overhead_value = models.DecimalField(max_digits=10, decimal_places=2, default=10)  # 10% default
    overhead_cost = models.DecimalField(max_digits=14, decimal_places=2, default=0)

    # Contingency buffer
    contingency_percent = models.DecimalField(max_digits=5, decimal_places=2, default=5)
    contingency_cost = models.DecimalField(max_digits=14, decimal_places=2, default=0)

    # Profit margin
    profit_percent = models.DecimalField(max_digits=5, decimal_places=2, default=20)
    profit_amount = models.DecimalField(max_digits=14, decimal_places=2, default=0)

    # Totals
    subtotal = models.DecimalField(max_digits=14, decimal_places=2, default=0)
    total_with_buffer = models.DecimalField(max_digits=14, decimal_places=2, default=0)
    total_cost = models.DecimalField(max_digits=14, decimal_places=2, default=0)

    # Budget comparison
    client_budget = models.DecimalField(max_digits=14, decimal_places=2, default=0)
    budget_status = models.CharField(max_length=20, default='pending')  # profitable, break_even, loss

    notes = models.TextField(blank=True)

    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='created_cost_sheets')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-version']
        unique_together = ['lead', 'version']

    def __str__(self):
        return f"CostSheet v{self.version} — {self.lead.title}"

    def calculate_totals(self):
        """Recalculate all costs from components."""
        from decimal import Decimal

        # HR Cost = sum of team member costs
        self.hr_cost = sum(
            m.total_cost for m in self.team_members.all()
        ) or Decimal('0')

        # Tools Cost = sum of tool items
        self.tools_cost = sum(
            t.cost for t in self.tool_items.all()
        ) or Decimal('0')

        # Overhead
        if self.overhead_type == 'percent':
            self.overhead_cost = self.hr_cost * (self.overhead_value / 100)
        else:
            self.overhead_cost = self.overhead_value

        # Subtotal = HR + Tools + Overhead
        self.subtotal = self.hr_cost + self.tools_cost + self.overhead_cost

        # Contingency = Subtotal × contingency%
        self.contingency_cost = self.subtotal * (self.contingency_percent / 100)
        self.total_with_buffer = self.subtotal + self.contingency_cost

        # Profit = total_with_buffer × profit%
        self.profit_amount = self.total_with_buffer * (self.profit_percent / 100)
        self.total_cost = self.total_with_buffer + self.profit_amount

        # Budget comparison
        self.client_budget = self.lead.proposed_budget or Decimal('0')
        if self.client_budget > 0:
            diff_pct = ((self.client_budget - self.total_cost) / self.client_budget) * 100
            if diff_pct > 5:
                self.budget_status = 'profitable'
            elif diff_pct >= -5:
                self.budget_status = 'break_even'
            else:
                self.budget_status = 'loss'
        else:
            self.budget_status = 'pending'

        self.save()


class CostSheetMember(models.Model):
    """A team member allocated to a cost sheet with estimated hours."""
    cost_sheet = models.ForeignKey(CostSheet, on_delete=models.CASCADE, related_name='team_members')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    project_role = models.CharField(max_length=100)  # Their role ON this project
    hourly_rate = models.DecimalField(max_digits=10, decimal_places=2)  # Snapshot from user
    estimated_hours = models.DecimalField(max_digits=8, decimal_places=2, default=0)
    total_cost = models.DecimalField(max_digits=14, decimal_places=2, default=0)

    class Meta:
        unique_together = ['cost_sheet', 'user']

    def save(self, *args, **kwargs):
        self.total_cost = self.hourly_rate * self.estimated_hours
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.user.full_name} — {self.estimated_hours}hrs @ {self.hourly_rate}/hr"


class CostSheetTool(models.Model):
    """Tool/license cost line item."""
    cost_sheet = models.ForeignKey(CostSheet, on_delete=models.CASCADE, related_name='tool_items')
    name = models.CharField(max_length=200)
    purpose = models.CharField(max_length=300, blank=True)
    cost = models.DecimalField(max_digits=12, decimal_places=2, default=0)

    def __str__(self):
        return f"{self.name} — PKR {self.cost}"
