import uuid
from decimal import Decimal
from django.db import models


class Account(models.Model):
    class AccountType(models.TextChoices):
        ASSET = "ASSET", "Asset"
        LIABILITY = "LIABILITY", "Liability"
        EQUITY = "EQUITY", "Equity"
        INCOME = "INCOME", "Income"
        EXPENSE = "EXPENSE", "Expense"

    class AccountClass(models.TextChoices):
        ASSET = "ASSET", "Asset (Normal Dr)"
        LIABILITY = "LIABILITY", "Liability (Normal Cr)"
        EQUITY = "EQUITY", "Capital / Equity (Normal Cr)"
        INCOME = "INCOME", "Income / Revenue (Normal Cr)"
        GAIN = "GAIN", "Gain (Normal Cr)"
        EXPENSE = "EXPENSE", "Expense (Normal Dr)"
        LOSS = "LOSS", "Loss (Normal Dr)"
        CONTRA_ASSET = "CONTRA_ASSET", "Contra Asset (Normal Cr)"
        CONTRA_INCOME = "CONTRA_INCOME", "Contra Income (Normal Dr)"

    class ControlRole(models.TextChoices):
        NONE = "NONE", "Regular Ledger Account"
        SUNDRY_DEBTORS = "SUNDRY_DEBTORS", "Sundry Debtors (Customer Control)"
        SUNDRY_CREDITORS = "SUNDRY_CREDITORS", "Sundry Creditors (Supplier Control)"
        SUBCONTRACTOR_PAYABLE = "SUBCONTRACTOR_PAYABLE", "Subcontractor Payable Control"
        RETENTION_RECEIVABLE = "RETENTION_RECEIVABLE", "Retention Receivable"
        RETENTION_PAYABLE = "RETENTION_PAYABLE", "Retention Payable"
        INVENTORY = "INVENTORY", "Inventory / Stock Control"
        GRNI = "GRNI", "Goods Received Not Invoiced (GRNI)"
        PROJECT_WIP = "PROJECT_WIP", "Project Work-in-Progress (WIP)"
        CASH = "CASH", "Cash in Hand"
        BANK = "BANK", "Bank Account"
        INPUT_VAT = "INPUT_VAT", "Input VAT Recoverable"
        OUTPUT_VAT = "OUTPUT_VAT", "Output VAT Payable"
        TDS_PAYABLE = "TDS_PAYABLE", "TDS Withholding Payable"
        TDS_RECEIVABLE = "TDS_RECEIVABLE", "TDS Advance Receivable"
        CUSTOMER_ADVANCE = "CUSTOMER_ADVANCE", "Customer / Mobilization Advance Liability"
        SUPPLIER_ADVANCE = "SUPPLIER_ADVANCE", "Supplier Advance Asset"
        EMPLOYEE_ADVANCE = "EMPLOYEE_ADVANCE", "Employee / Staff Advance"
        EMPLOYEE_PAYABLE = "EMPLOYEE_PAYABLE", "Employee Payables"
        WAGES_PAYABLE = "WAGES_PAYABLE", "Wages Payable"
        PF_SSF_PAYABLE = "PF_SSF_PAYABLE", "PF / SSF / CIT Statutory Payable"
        EMPLOYEE_REIMBURSEMENT = "EMPLOYEE_REIMBURSEMENT", "Employee Reimbursement Payable"
        STAFF_LOAN_RECEIVABLE = "STAFF_LOAN_RECEIVABLE", "Staff Loan Receivable"
        OFFICE_EXPENSES = "OFFICE_EXPENSES", "Office & Administrative Expenses"
        DIRECT_EXPENSES = "DIRECT_EXPENSES", "Direct Construction Expenses"
        OUTSTANDING_EXPENSES = "OUTSTANDING_EXPENSES", "Outstanding / Accrued Expenses"
        OTHER_INCOME = "OTHER_INCOME", "Other Income & Gains"
        LOSS_WRITE_OFF = "LOSS_WRITE_OFF", "Losses & Write-offs"
        BAD_DEBT_ALLOWANCE = "BAD_DEBT_ALLOWANCE", "Allowance / Provision for Doubtful Debts"
        FX_GAIN = "FX_GAIN", "Foreign Exchange Gain"
        FX_LOSS = "FX_LOSS", "Foreign Exchange Loss"
        DEPRECIATION_EXP = "DEPRECIATION_EXP", "Depreciation Expense"
        ACCUM_DEPRECIATION = "ACCUM_DEPRECIATION", "Accumulated Depreciation (Contra Asset)"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="accounts")
    parent = models.ForeignKey(
        "self", on_delete=models.PROTECT, null=True, blank=True, related_name="children"
    )
    code = models.CharField(max_length=32)
    name = models.CharField(max_length=200)
    account_type = models.CharField(max_length=16, choices=AccountType.choices)
    account_class = models.CharField(
        max_length=20, choices=AccountClass.choices, blank=True, default=""
    )
    control_role = models.CharField(
        max_length=28, choices=ControlRole.choices, default=ControlRole.NONE, db_index=True
    )
    nfrs_mapping = models.CharField(max_length=64, blank=True)
    is_group = models.BooleanField(default=False)
    is_control_account = models.BooleanField(default=False)
    requires_subledger = models.BooleanField(default=False)
    allow_direct_posting = models.BooleanField(default=True)
    opening_debit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    opening_credit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    is_active = models.BooleanField(default=True)

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

    def save(self, *args, **kwargs):
        if not self.account_class:
            self.account_class = self.account_type
        if self.control_role in (
            self.ControlRole.SUNDRY_DEBTORS,
            self.ControlRole.SUNDRY_CREDITORS,
            self.ControlRole.SUBCONTRACTOR_PAYABLE,
            self.ControlRole.EMPLOYEE_PAYABLE,
            self.ControlRole.WAGES_PAYABLE,
        ):
            self.is_control_account = True
            self.requires_subledger = True
        super().save(*args, **kwargs)

    @property
    def effective_class(self) -> str:
        return self.account_class or self.account_type

    @property
    def normal_balance(self) -> str:
        if self.effective_class in (
            self.AccountClass.ASSET,
            self.AccountClass.EXPENSE,
            self.AccountClass.LOSS,
            self.AccountClass.CONTRA_INCOME,
        ):
            return "DEBIT"
        return "CREDIT"

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


class Department(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="departments")
    code = models.CharField(max_length=24)
    name = models.CharField(max_length=120)
    is_active = models.BooleanField(default=True)

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

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


class CostCategory(models.Model):
    """Tally-style Cost Category grouping Cost Centres (e.g., Departments, Construction Projects, Equipment)."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="cost_categories")
    code = models.CharField(max_length=24)
    name = models.CharField(max_length=120)
    allocate_revenue = models.BooleanField(default=True)
    allocate_non_revenue = models.BooleanField(default=True)
    is_active = models.BooleanField(default=True)

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

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


class CostCenter(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="cost_centers")
    cost_category = models.ForeignKey(
        CostCategory, on_delete=models.SET_NULL, null=True, blank=True, related_name="cost_centers"
    )
    parent = models.ForeignKey(
        "self", on_delete=models.PROTECT, null=True, blank=True, related_name="children"
    )
    project = models.ForeignKey(
        "projects.Project", on_delete=models.PROTECT, null=True, blank=True, related_name="cost_centers"
    )
    site = models.ForeignKey(
        "projects.Site", on_delete=models.SET_NULL, null=True, blank=True, related_name="cost_centers"
    )
    cost_code = models.ForeignKey(
        "projects.CostCode", on_delete=models.SET_NULL, null=True, blank=True, related_name="cost_centers"
    )
    code = models.CharField(max_length=24)
    name = models.CharField(max_length=150)
    is_active = models.BooleanField(default=True)

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

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


class WorkPackage(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    project = models.ForeignKey("projects.Project", on_delete=models.CASCADE, related_name="work_packages")
    code = models.CharField(max_length=32)
    name = models.CharField(max_length=180)
    budget_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    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 BoqItem(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="boq_items")
    project = models.ForeignKey("projects.Project", on_delete=models.CASCADE, related_name="boq_items")
    work_package = models.ForeignKey(
        WorkPackage, on_delete=models.SET_NULL, null=True, blank=True, related_name="boq_items"
    )
    cost_code = models.ForeignKey(
        "projects.CostCode", on_delete=models.PROTECT, null=True, blank=True
    )
    code = models.CharField(max_length=40)
    description = models.CharField(max_length=255)
    unit = models.CharField(max_length=24, default="Cum")
    boq_quantity = models.DecimalField(max_digits=18, decimal_places=3, default=Decimal("0.000"))
    unit_rate = 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"))
    is_active = models.BooleanField(default=True)

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

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


class EquipmentAsset(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="equipment_assets")
    code = models.CharField(max_length=32)
    name = models.CharField(max_length=160)
    asset_category = models.CharField(max_length=64, default="Heavy Machinery")
    hourly_rate = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    linked_asset_account = models.ForeignKey(
        Account, on_delete=models.PROTECT, null=True, blank=True, related_name="equipment_assets"
    )
    is_active = models.BooleanField(default=True)

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

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


class AccountRelationship(models.Model):
    """Database-driven rule mapping parent/control accounts to related subledgers, child accounts, and selectors."""

    class TargetKind(models.TextChoices):
        SUPPLIER_CONTRACTOR = "SUPPLIER_CONTRACTOR", "Suppliers & Contractors (Creditors)"
        CUSTOMER_CLIENT = "CUSTOMER_CLIENT", "Customers & Clients (Debtors)"
        CHILD_EXPENSE = "CHILD_EXPENSE", "Child Expense Ledgers"
        DIRECT_EXPENSE = "DIRECT_EXPENSE", "Direct Construction Expense Ledgers"
        EMPLOYEE = "EMPLOYEE", "Employees & Staff Ledgers"
        EMPLOYEE_ADVANCE = "EMPLOYEE_ADVANCE", "Employees with Outstanding Advances"
        SUPPLIER_ADVANCE = "SUPPLIER_ADVANCE", "Suppliers with Outstanding Advances"
        CUSTOMER_ADVANCE = "CUSTOMER_ADVANCE", "Customers with Outstanding Advances"
        STAFF_LOAN = "STAFF_LOAN", "Staff Loans Receivable"
        PROJECT_WIP = "PROJECT_WIP", "Projects, Sites, BOQ & Cost Codes"
        BANK_ACCOUNT = "BANK_ACCOUNT", "Registered Bank Accounts"
        CASH_ACCOUNT = "CASH_ACCOUNT", "Cash & Petty Cash Accounts"
        PURCHASE_SUB = "PURCHASE_SUB", "Purchase Subaccounts"
        SALES_SUB = "SALES_SUB", "Sales & Revenue Accounts"
        INCOME_SUB = "INCOME_SUB", "Other Income & Gains"
        LOSS_SUB = "LOSS_SUB", "Loss & Write-off Accounts"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="account_relationships")
    account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="relationships")
    target_kind = models.CharField(max_length=28, choices=TargetKind.choices)
    extra_selector = models.CharField(max_length=40, blank=True, default="")
    suggested_counter_account = models.ForeignKey(
        Account, on_delete=models.SET_NULL, null=True, blank=True, related_name="counter_for_relationships"
    )
    require_project = models.BooleanField(default=False)
    require_subledger = models.BooleanField(default=False)
    require_reason_on_journal = models.BooleanField(default=False)
    allow_direct_journal_adjustment = models.BooleanField(default=True)
    notes = models.CharField(max_length=255, blank=True)
    is_active = models.BooleanField(default=True)

    class Meta:
        db_table = "account_relationships"
        unique_together = [("company", "account", "target_kind")]
        ordering = ["account__code"]

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


