import uuid
from decimal import Decimal
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models

from apps.localization.bs_calendar import ad_to_bs
from .project_master import CostCode, Project


class Site(models.Model):
    class SiteType(models.TextChoices):
        MAIN = "MAIN", "Main Worksite"
        TEMPORARY = "TEMPORARY", "Temporary Site / Camp"
        REMOTE = "REMOTE", "Remote Site"
        SECTION = "SECTION", "Chainage / Section"

    class Status(models.TextChoices):
        PLANNED = "PLANNED", "Planned"
        ACTIVE = "ACTIVE", "Active"
        SUSPENDED = "SUSPENDED", "Suspended"
        COMPLETED = "COMPLETED", "Completed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="sites")
    code = models.CharField(max_length=32)
    name = models.CharField(max_length=150)
    site_type = models.CharField(max_length=16, choices=SiteType.choices, default=SiteType.MAIN)
    province = models.CharField(max_length=64, blank=True)
    district = models.CharField(max_length=64, blank=True)
    municipality = models.CharField(max_length=120, blank=True)
    ward_no = models.CharField(max_length=20, blank=True)
    location = models.CharField(max_length=200, 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_manager = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="managed_sites"
    )
    site_engineer = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="engineered_sites"
    )
    site_supervisor = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="supervised_sites"
    )
    site_accountant = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="accounted_sites"
    )

    site_store = models.ForeignKey(
        "inventory.Warehouse", on_delete=models.SET_NULL, null=True, blank=True, related_name="linked_sites"
    )
    site_cash_account = models.ForeignKey(
        "banking.CashAccount", on_delete=models.SET_NULL, null=True, blank=True, related_name="linked_sites"
    )
    site_cost_center = models.ForeignKey(
        "accounting.CostCenter", on_delete=models.SET_NULL, null=True, blank=True, related_name="linked_sites"
    )

    start_date = models.DateField(null=True, blank=True)
    expected_completion_date = models.DateField(null=True, blank=True)
    actual_completion_date = models.DateField(null=True, blank=True)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.ACTIVE)
    is_active = models.BooleanField(default=True)

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

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


class ProjectBoqHeader(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="boq_headers")
    boq_no = models.CharField(max_length=48)
    title = models.CharField(max_length=200)
    version = models.PositiveSmallIntegerField(default=1)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "project_boqs"
        unique_together = [("project", "boq_no")]
        ordering = ["-version", "boq_no"]


class ProjectBoqLine(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    boq_header = models.ForeignKey(ProjectBoqHeader, on_delete=models.CASCADE, related_name="items")
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="project_boq_items")
    boq_item = models.ForeignKey(
        "accounting.BoqItem", on_delete=models.SET_NULL, null=True, blank=True, related_name="project_boq_lines"
    )
    work_package = models.ForeignKey("accounting.WorkPackage", on_delete=models.SET_NULL, null=True, blank=True)
    cost_code = models.ForeignKey(CostCode, on_delete=models.SET_NULL, null=True, blank=True)
    item_code = models.CharField(max_length=40)
    description = models.CharField(max_length=255)
    unit = models.CharField(max_length=24, default="Cum")
    contract_qty = models.DecimalField(max_digits=18, decimal_places=3, default=Decimal("0.000"))
    contract_rate = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    revised_qty = models.DecimalField(max_digits=18, decimal_places=3, default=Decimal("0.000"))
    revised_rate = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    completed_qty = models.DecimalField(max_digits=18, decimal_places=3, default=Decimal("0.000"))
    previous_certified_qty = models.DecimalField(max_digits=18, decimal_places=3, default=Decimal("0.000"))
    current_measured_qty = models.DecimalField(max_digits=18, decimal_places=3, default=Decimal("0.000"))

    class Meta:
        db_table = "project_boq_items"
        ordering = ["item_code"]

    @property
    def original_amount(self) -> Decimal:
        return (self.contract_qty * self.contract_rate).quantize(Decimal("0.01"))

    @property
    def approved_revised_amount(self) -> Decimal:
        q = self.revised_qty if self.revised_qty > 0 else self.contract_qty
        r = self.revised_rate if self.revised_rate > 0 else self.contract_rate
        return (q * r).quantize(Decimal("0.01"))

    @property
    def remaining_qty(self) -> Decimal:
        base = self.revised_qty if self.revised_qty > 0 else self.contract_qty
        rem = base - self.completed_qty
        return rem if rem > Decimal("0.000") else Decimal("0.000")


class ProjectWbsNode(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="wbs_nodes")
    parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children")
    work_package = models.ForeignKey("accounting.WorkPackage", on_delete=models.SET_NULL, null=True, blank=True)
    code = models.CharField(max_length=40)
    name = models.CharField(max_length=180)
    level_type = models.CharField(max_length=24, default="PACKAGE")  # PACKAGE | WORK_GROUP | SUB_WORK
    planned_weight_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0.00"))

    class Meta:
        db_table = "project_wbs"
        unique_together = [("project", "code")]
        ordering = ["code"]


class ProjectActivity(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="activities")
    site = models.ForeignKey(Site, on_delete=models.SET_NULL, null=True, blank=True, related_name="activities")
    wbs_node = models.ForeignKey(ProjectWbsNode, on_delete=models.SET_NULL, null=True, blank=True, related_name="activities")
    boq_line = models.ForeignKey(ProjectBoqLine, on_delete=models.SET_NULL, null=True, blank=True, related_name="activities")
    predecessor = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="successors")
    code = models.CharField(max_length=40)
    name = models.CharField(max_length=200)
    unit = models.CharField(max_length=24, default="Units")
    planned_qty = models.DecimalField(max_digits=14, decimal_places=3, default=Decimal("0.000"))
    completed_qty = models.DecimalField(max_digits=14, decimal_places=3, default=Decimal("0.000"))
    progress_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0.00"))
    daily_production_target = models.DecimalField(max_digits=12, decimal_places=3, default=Decimal("0.000"))
    planned_start = models.DateField(null=True, blank=True)
    planned_end = models.DateField(null=True, blank=True)
    actual_start = models.DateField(null=True, blank=True)
    actual_end = models.DateField(null=True, blank=True)
    delay_days = models.IntegerField(default=0)
    delay_reason = models.CharField(max_length=255, blank=True)
    status = models.CharField(max_length=16, default="PLANNED")

    class Meta:
        db_table = "project_activities"
        unique_together = [("project", "code")]
        ordering = ["planned_start", "code"]


class ProjectProgress(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="progress_records")
    site = models.ForeignKey(Site, on_delete=models.SET_NULL, null=True, blank=True)
    activity = models.ForeignKey(ProjectActivity, on_delete=models.SET_NULL, null=True, blank=True)
    period_label = models.CharField(max_length=40)
    report_date = models.DateField(db_index=True)
    bs_date = models.CharField(max_length=16, blank=True)
    planned_progress_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0.00"))
    actual_progress_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0.00"))
    measured_qty = models.DecimalField(max_digits=14, decimal_places=3, default=Decimal("0.000"))
    remarks = models.CharField(max_length=255, blank=True)
    recorded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "project_progress"
        ordering = ["report_date", "created_at"]

    def save(self, *args, **kwargs):
        if self.report_date and not self.bs_date:
            self.bs_date = ad_to_bs(self.report_date).isoformat()
        super().save(*args, **kwargs)


class DailySiteReport(models.Model):
    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        SUBMITTED = "SUBMITTED", "Submitted"
        APPROVED = "APPROVED", "Approved"

    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="daily_reports")
    site = models.ForeignKey(Site, on_delete=models.CASCADE, related_name="daily_reports")
    report_date = models.DateField(db_index=True)
    bs_date = models.CharField(max_length=16, blank=True)
    weather = models.CharField(max_length=80, blank=True)
    work_performed = models.TextField()
    boq_line = models.ForeignKey(ProjectBoqLine, on_delete=models.SET_NULL, null=True, blank=True)
    activity = models.ForeignKey(ProjectActivity, on_delete=models.SET_NULL, null=True, blank=True)
    quantity_completed = models.DecimalField(max_digits=14, decimal_places=3, default=Decimal("0.000"))
    skilled_workers = models.PositiveIntegerField(default=0)
    unskilled_workers = models.PositiveIntegerField(default=0)
    equipment_utilized = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    materials_consumed = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    delays = models.CharField(max_length=255, blank=True)
    safety_observations = models.TextField(blank=True)
    quality_observations = models.TextField(blank=True)
    photographs = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    idempotency_key = models.CharField(max_length=128, null=True, blank=True)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.SUBMITTED)
    prepared_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="prepared_dsrs"
    )
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="approved_dsrs"
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "project_daily_reports"
        constraints = [
            models.UniqueConstraint(fields=["company", "idempotency_key"], name="uniq_dsr_cmp_idem")
        ]
        ordering = ["-report_date", "-created_at"]

    def save(self, *args, **kwargs):
        if self.report_date and not self.bs_date:
            self.bs_date = ad_to_bs(self.report_date).isoformat()
        super().save(*args, **kwargs)


class SiteInspectionSafetyLog(models.Model):
    class LogKind(models.TextChoices):
        QUALITY_INSPECTION = "QUALITY_INSPECTION", "Quality Inspection"
        SAFETY_INCIDENT = "SAFETY_INCIDENT", "Safety Observation / Incident"

    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="qa_hse_logs")
    site = models.ForeignKey(Site, on_delete=models.CASCADE, related_name="qa_hse_logs")
    log_kind = models.CharField(max_length=24, choices=LogKind.choices)
    log_date = models.DateField()
    bs_date = models.CharField(max_length=16, blank=True)
    title = models.CharField(max_length=200)
    severity_or_result = models.CharField(max_length=32, default="PASS")  # PASS | FAIL | CONDITIONAL | LOW | MEDIUM | HIGH
    notes = models.TextField(blank=True)
    recorded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "project_site_qa_hse"
        ordering = ["-log_date", "-created_at"]

    def save(self, *args, **kwargs):
        if self.log_date and not self.bs_date:
            self.bs_date = ad_to_bs(self.log_date).isoformat()
        super().save(*args, **kwargs)


class ProjectDocument(models.Model):
    class Category(models.TextChoices):
        CONTRACT_AGREEMENT = "CONTRACT_AGREEMENT", "Contract Agreement"
        LETTER_OF_AWARD = "LETTER_OF_AWARD", "Letter of Award"
        BOQ = "BOQ", "Bill of Quantities (BOQ)"
        APPROVED_DRAWINGS = "APPROVED_DRAWINGS", "Approved Drawings"
        DESIGN_DOCUMENTS = "DESIGN_DOCUMENTS", "Design Documents"
        INSURANCE_CERTIFICATES = "INSURANCE_CERTIFICATES", "Insurance Certificates"
        PERFORMANCE_GUARANTEES = "PERFORMANCE_GUARANTEES", "Performance Guarantees"
        ADVANCE_GUARANTEES = "ADVANCE_GUARANTEES", "Advance Guarantees"
        WORK_PROGRAM = "WORK_PROGRAM", "Work Program"
        VARIATION_ORDERS = "VARIATION_ORDERS", "Variation Orders"
        MEASUREMENT_BOOKS = "MEASUREMENT_BOOKS", "Measurement Books"
        RA_BILLS = "RA_BILLS", "RA Bills"
        SITE_INSTRUCTIONS = "SITE_INSTRUCTIONS", "Site Instructions"
        INSPECTION_REPORTS = "INSPECTION_REPORTS", "Inspection Reports"
        COMPLETION_CERTIFICATES = "COMPLETION_CERTIFICATES", "Completion Certificates"
        HANDOVER_DOCUMENTS = "HANDOVER_DOCUMENTS", "Handover Documents"
        FINAL_SETTLEMENT = "FINAL_SETTLEMENT", "Final Settlement Statements"

    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="project_documents")
    site = models.ForeignKey(Site, on_delete=models.SET_NULL, null=True, blank=True, related_name="site_documents")
    category = models.CharField(max_length=32, choices=Category.choices)
    title = models.CharField(max_length=200)
    file_name = models.CharField(max_length=200)
    storage_key = models.CharField(max_length=255, blank=True)
    mime_type = models.CharField(max_length=120, blank=True)
    file_size_bytes = models.PositiveIntegerField(default=0)
    sha256_hash = models.CharField(max_length=64, blank=True)
    version = models.PositiveIntegerField(default=1)
    expiry_date = models.DateField(null=True, blank=True)
    is_restricted = models.BooleanField(default=False)
    approval_status = models.CharField(max_length=16, default="APPROVED")
    linked_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="project_documents"
    )
    uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    uploaded_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "project_documents"
        ordering = ["-uploaded_at"]


class ProjectApproval(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="approvals")
    entity_type = models.CharField(max_length=40)
    entity_id = models.CharField(max_length=64)
    action = models.CharField(max_length=24)
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    comment = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "project_approvals"
        ordering = ["-created_at"]


class ProjectAuditLog(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="audit_logs")
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True)
    action = models.CharField(max_length=64)
    entity_type = models.CharField(max_length=48)
    entity_id = models.CharField(max_length=64)
    previous_state = models.JSONField(null=True, blank=True, encoder=DjangoJSONEncoder)
    new_state = models.JSONField(null=True, blank=True, encoder=DjangoJSONEncoder)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "project_audit_logs"
        ordering = ["-created_at"]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            raise PermissionError("ProjectAuditLog records are immutable.")
        super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        raise PermissionError("ProjectAuditLog records cannot be deleted.")
