import uuid
from decimal import Decimal
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models


class Project(models.Model):
    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        PLANNED = "PLANNED", "Planning"
        AWARDED = "AWARDED", "Awarded"
        ACTIVE = "ACTIVE", "Active"
        SUSPENDED = "SUSPENDED", "Suspended"
        ON_HOLD = "ON_HOLD", "On Hold"
        COMPLETED = "COMPLETED", "Completed"
        CLOSED = "CLOSED", "Closed"

    class Classification(models.TextChoices):
        INFRASTRUCTURE = "INFRASTRUCTURE", "Infrastructure"
        BUILDING = "BUILDING", "Building"
        ROAD = "ROAD", "Road"
        BRIDGE = "BRIDGE", "Bridge"
        HYDROPOWER = "HYDROPOWER", "Hydropower"
        IRRIGATION = "IRRIGATION", "Irrigation"
        CIVIL_WORKS = "CIVIL_WORKS", "Civil Works"

    class ContractType(models.TextChoices):
        LUMP_SUM = "LUMP_SUM", "Lump Sum"
        ITEM_RATE = "ITEM_RATE", "Item Rate"
        UNIT_RATE = "UNIT_RATE", "Unit Rate"
        EPC = "EPC", "EPC"
        DESIGN_BUILD = "DESIGN_BUILD", "Design-Build"
        COST_PLUS = "COST_PLUS", "Cost Plus"

    class ProcurementMethod(models.TextChoices):
        OPEN_TENDER = "OPEN_TENDER", "Open Tender"
        LIMITED_TENDER = "LIMITED_TENDER", "Limited Tender"
        DIRECT_PROCUREMENT = "DIRECT_PROCUREMENT", "Direct Procurement"
        NEGOTIATED = "NEGOTIATED", "Negotiated"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="projects")
    code = models.CharField(max_length=32, db_index=True)
    contract_reference = models.CharField(max_length=80, blank=True, db_index=True)
    name = models.CharField(max_length=200)
    client_party = models.ForeignKey(
        "accounting.Party",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="client_projects",
    )
    client_name = models.CharField(max_length=200, blank=True)
    location = models.CharField(max_length=200, blank=True)

    # Strict Financial Separation: Original Contract Value vs Approved Value vs Cost Budget Ceiling
    contract_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    approved_contract_value = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    budget_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))

    retention_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("5.00"))
    retention_ceiling = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    mobilization_advance_permitted = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))

    # Classification & Parties
    project_classification = models.CharField(
        max_length=24, choices=Classification.choices, default=Classification.CIVIL_WORKS
    )
    contract_type = models.CharField(
        max_length=24, choices=ContractType.choices, default=ContractType.ITEM_RATE
    )
    procurement_method = models.CharField(
        max_length=24, choices=ProcurementMethod.choices, default=ProcurementMethod.OPEN_TENDER
    )
    consultant_name = models.CharField(max_length=200, blank=True)
    consultant_engineer = models.CharField(max_length=160, blank=True)
    main_contractor = models.CharField(max_length=200, blank=True)
    jv_partners = models.CharField(max_length=255, blank=True)

    # Contractual & Execution Dates
    award_date = models.DateField(null=True, blank=True)
    contract_signing_date = models.DateField(null=True, blank=True)
    start_date = models.DateField(null=True, blank=True)
    actual_start_date = models.DateField(null=True, blank=True)
    expected_end_date = models.DateField(null=True, blank=True)
    revised_end_date = models.DateField(null=True, blank=True)
    actual_end_date = models.DateField(null=True, blank=True)
    defects_liability_months = models.PositiveSmallIntegerField(default=12)
    defects_liability_end_date = models.DateField(null=True, blank=True)

    # Accounting & Leadership
    fiscal_year = models.ForeignKey(
        "tenancy.FiscalYear", on_delete=models.SET_NULL, null=True, blank=True, related_name="projects"
    )
    currency = models.CharField(max_length=3, default="NPR")
    project_manager = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="managed_projects"
    )
    project_accountant = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="accounted_projects"
    )
    site_engineer = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="engineered_projects"
    )

    status = models.CharField(max_length=16, choices=Status.choices, default=Status.ACTIVE, db_index=True)
    registration_step = models.PositiveSmallIntegerField(default=1)
    is_draft = models.BooleanField(default=False)
    theme_code = models.CharField(max_length=24, default="CONSTRUCTION_TEAL")
    description = models.TextField(blank=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="created_projects"
    )
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="approved_projects"
    )
    activated_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        unique_together = [("company", "code")]
        ordering = ["code"]
        indexes = [
            models.Index(fields=["company", "status"], name="idx_prj_cmp_stat"),
        ]

    def clean(self):
        if self.contract_amount < 0 or self.approved_contract_value < 0 or self.budget_amount < 0:
            raise ValidationError("Contract values and cost budget ceiling must be non-negative.")

    def save(self, *args, **kwargs):
        if self.client_party and not self.client_name:
            self.client_name = self.client_party.name
        super().save(*args, **kwargs)

    def __str__(self) -> str:
        return f"{self.code} — {self.name}"


class CostCode(models.Model):
    class Category(models.TextChoices):
        MATERIAL = "MATERIAL", "Materials"
        LABOR = "LABOR", "Labor"
        EQUIPMENT = "EQUIPMENT", "Equipment"
        SUBCONTRACT = "SUBCONTRACT", "Subcontract"
        TRANSPORT = "TRANSPORT", "Transport"
        OVERHEAD = "OVERHEAD", "Overheads"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="cost_codes")
    code = models.CharField(max_length=32)
    name = models.CharField(max_length=150)
    category = models.CharField(max_length=16, choices=Category.choices)
    is_active = models.BooleanField(default=True)

    class Meta:
        unique_together = [("company", "code")]
        ordering = ["code"]

    def __str__(self) -> str:
        return f"{self.code} — {self.name} ({self.category})"


class ProjectClient(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="clients")
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, null=True, blank=True)
    organization_name = models.CharField(max_length=200)
    client_code = models.CharField(max_length=40, blank=True)
    pan_vat_no = models.CharField(max_length=20, blank=True)
    contact_person = models.CharField(max_length=120, blank=True)
    telephone = models.CharField(max_length=40, blank=True)
    email = models.EmailField(blank=True)
    address = models.CharField(max_length=255, blank=True)
    is_primary = models.BooleanField(default=True)

    class Meta:
        db_table = "project_clients"
        ordering = ["-is_primary", "organization_name"]


class ProjectLocation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="locations")
    country = models.CharField(max_length=64, default="Nepal")
    province = models.CharField(max_length=64, blank=True)
    district = models.CharField(max_length=64, blank=True)
    local_level_type = models.CharField(max_length=40, blank=True)
    municipality = models.CharField(max_length=120, blank=True)
    ward_no = models.CharField(max_length=20, blank=True)
    address = models.CharField(max_length=255, blank=True)
    gps_latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
    gps_longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
    site_area = models.CharField(max_length=80, blank=True)
    access_route = models.CharField(max_length=255, blank=True)
    is_primary = models.BooleanField(default=False)

    class Meta:
        db_table = "project_locations"
        ordering = ["-is_primary", "province", "district"]


class ProjectTeamMember(models.Model):
    class ProjectRole(models.TextChoices):
        PROJECT_DIRECTOR = "PROJECT_DIRECTOR", "Project Director"
        PROJECT_MANAGER = "PROJECT_MANAGER", "Project Manager"
        PROJECT_ENGINEER = "PROJECT_ENGINEER", "Project Engineer"
        SITE_ENGINEER = "SITE_ENGINEER", "Site Engineer"
        SITE_SUPERVISOR = "SITE_SUPERVISOR", "Site Supervisor"
        PROJECT_ACCOUNTANT = "PROJECT_ACCOUNTANT", "Project Accountant"
        QUANTITY_SURVEYOR = "QUANTITY_SURVEYOR", "Quantity Surveyor"
        PROCUREMENT_OFFICER = "PROCUREMENT_OFFICER", "Procurement Officer"
        STOREKEEPER = "STOREKEEPER", "Storekeeper"
        SAFETY_OFFICER = "SAFETY_OFFICER", "Safety Officer"
        QUALITY_ENGINEER = "QUALITY_ENGINEER", "Quality Engineer"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="team_members")
    site = models.ForeignKey("projects.Site", on_delete=models.SET_NULL, null=True, blank=True, related_name="team_members")
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="project_assignments")
    employee = models.ForeignKey(
        "accounting.EmployeeProfile", on_delete=models.SET_NULL, null=True, blank=True
    )
    department = models.ForeignKey(
        "accounting.Department", on_delete=models.SET_NULL, null=True, blank=True
    )
    project_role = models.CharField(max_length=28, choices=ProjectRole.choices)
    responsibility_notes = models.CharField(max_length=255, blank=True)
    can_approve_dsr = models.BooleanField(default=False)
    can_approve_variations = models.BooleanField(default=False)
    can_manage_store = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    assigned_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "project_team_members"
        unique_together = [("project", "user", "project_role", "site")]
        ordering = ["project_role", "user__username"]

