from decimal import Decimal
from django.core.exceptions import ValidationError
from django.db import transaction
from django.utils import timezone

from apps.accounting.models import Account, CostCenter, Party
from apps.audit.services import record_audit_event
from apps.banking.models import CashAccount
from apps.inventory.models import Warehouse
from apps.projects.models import (
    Project,
    ProjectAuditLog,
    ProjectApproval,
    ProjectBudget,
    ProjectBudgetVersion,
    ProjectClient,
    ProjectContract,
    ProjectLocation,
    ProjectMilestone,
    ProjectTeamMember,
    Site,
)
from apps.tenancy.models import FiscalYear


DEFAULT_MILESTONES = [
    (ProjectMilestone.MilestoneKind.CONTRACT_SIGNING, "Contract Signing"),
    (ProjectMilestone.MilestoneKind.ADVANCE_PAYMENT, "Advance Payment"),
    (ProjectMilestone.MilestoneKind.SITE_HANDOVER, "Site Handover"),
    (ProjectMilestone.MilestoneKind.MOBILIZATION, "Mobilization"),
    (ProjectMilestone.MilestoneKind.COMMENCEMENT, "Commencement"),
    (ProjectMilestone.MilestoneKind.FOUNDATION, "Foundation Completion"),
    (ProjectMilestone.MilestoneKind.STRUCTURAL, "Structural Completion"),
    (ProjectMilestone.MilestoneKind.DELIVERY, "Major Delivery Milestone"),
    (ProjectMilestone.MilestoneKind.TESTING_COMMISSIONING, "Testing & Commissioning"),
    (ProjectMilestone.MilestoneKind.PRACTICAL_COMPLETION, "Practical Completion"),
    (ProjectMilestone.MilestoneKind.FINAL_HANDOVER, "Final Handover"),
    (ProjectMilestone.MilestoneKind.DEFECTS_LIABILITY, "Defects Liability Completion"),
    (ProjectMilestone.MilestoneKind.FINAL_SETTLEMENT, "Final Account Settlement"),
]


def log_project_audit(
    *,
    project: Project,
    actor,
    action: str,
    entity_type: str,
    entity_id: str,
    previous_state: dict | None = None,
    new_state: dict | None = None,
):
    ProjectAuditLog.objects.create(
        company=project.company,
        project=project,
        actor=actor,
        action=action,
        entity_type=entity_type,
        entity_id=str(entity_id),
        previous_state=previous_state,
        new_state=new_state,
    )
    record_audit_event(
        company=project.company,
        actor=actor,
        action=action,
        entity_type=f"Project:{entity_type}",
        entity_id=str(entity_id),
        previous_state=previous_state,
        new_state=new_state,
    )


class ProjectMasterService:
    @staticmethod
    @transaction.atomic
    def sync_project_satellite_records(*, project: Project, data: dict, user):
        # Strictly maintain Contract, Client, Budget & Locations independently
        orig_val = project.contract_amount or Decimal("0.00")
        app_val = project.approved_contract_value if project.approved_contract_value > 0 else orig_val
        if project.approved_contract_value == 0 and orig_val > 0 and not data.get("explicit_approved_contract_value"):
            app_val = orig_val
            project.approved_contract_value = app_val
            project.save(update_fields=["approved_contract_value"])

        contract, _ = ProjectContract.objects.get_or_create(
            project=project,
            defaults={
                "company": project.company,
                "contract_no": project.contract_reference or f"CON-{project.code}",
                "original_contract_value": orig_val,
                "approved_contract_value": app_val,
                "approved_cost_budget": project.budget_amount or Decimal("0.00"),
                "retention_rate": project.retention_rate,
                "retention_ceiling": project.retention_ceiling,
                "mobilization_advance_permitted": project.mobilization_advance_permitted,
            },
        )
        # Keep contract header aligned on draft creation/update without conflating contract vs budget
        contract.contract_no = project.contract_reference or contract.contract_no
        contract.original_contract_value = project.contract_amount
        contract.approved_contract_value = project.approved_contract_value
        contract.approved_cost_budget = project.budget_amount
        contract.retention_rate = project.retention_rate
        contract.retention_ceiling = project.retention_ceiling
        contract.mobilization_advance_permitted = project.mobilization_advance_permitted
        contract.save()

        if project.client_party_id and not project.clients.exists():
            p: Party = project.client_party
            ProjectClient.objects.create(
                company=project.company,
                project=project,
                party=p,
                organization_name=p.name,
                client_code=p.code,
                pan_vat_no=p.pan_vat_no,
                telephone=p.phone,
                email=p.email,
                address=p.address,
                is_primary=True,
            )

        fy = project.fiscal_year or FiscalYear.objects.filter(company=project.company, is_current=True).first()
        if fy and not project.project_budgets.exists():
            pb = ProjectBudget.objects.create(
                company=project.company,
                project=project,
                fiscal_year=fy,
                original_ceiling=project.budget_amount or Decimal("0.00"),
                approved_ceiling=project.budget_amount or Decimal("0.00"),
                estimated_cost_to_complete=Decimal("0.00"),
            )
            ProjectBudgetVersion.objects.create(
                project_budget=pb,
                version_no=1,
                ceiling_amount=project.budget_amount or Decimal("0.00"),
                reason="Initial Approved Cost Budget Ceiling",
                approved_by=user,
            )

        # Optional nested locations & team members from wizard payload
        for loc in data.get("locations_payload") or []:
            ProjectLocation.objects.create(
                company=project.company,
                project=project,
                country=loc.get("country") or "Nepal",
                province=loc.get("province") or "",
                district=loc.get("district") or "",
                local_level_type=loc.get("local_level_type") or "",
                municipality=loc.get("municipality") or "",
                ward_no=loc.get("ward_no") or "",
                address=loc.get("address") or "",
                gps_latitude=loc.get("gps_latitude") or None,
                gps_longitude=loc.get("gps_longitude") or None,
                site_area=loc.get("site_area") or "",
                access_route=loc.get("access_route") or "",
                is_primary=bool(loc.get("is_primary", False)),
            )

        for tm in data.get("team_payload") or []:
            if tm.get("user") and tm.get("project_role"):
                ProjectTeamMember.objects.get_or_create(
                    company=project.company,
                    project=project,
                    user_id=tm["user"],
                    project_role=tm["project_role"],
                    site_id=tm.get("site") or None,
                    defaults={"responsibility_notes": tm.get("responsibility_notes") or ""},
                )

    @staticmethod
    @transaction.atomic
    def activate_project(*, project: Project, user, comment: str = "") -> Project:
        if not project.code or not project.name:
            raise ValidationError("Project Code and Project Name are required to activate a project.")
        prev = project.status
        project.is_draft = False
        project.status = Project.Status.ACTIVE
        project.approved_by = user
        project.activated_at = timezone.now()
        project.registration_step = 6
        project.save(update_fields=["is_draft", "status", "approved_by", "activated_at", "registration_step", "updated_at"])

        if not project.milestones.exists():
            for idx, (kind, title) in enumerate(DEFAULT_MILESTONES, start=1):
                ProjectMilestone.objects.create(
                    company=project.company,
                    project=project,
                    milestone_kind=kind,
                    title=title,
                    sequence=idx,
                    owner=project.project_manager or user,
                    planned_date=project.start_date if idx <= 5 else project.expected_end_date,
                )

        ProjectApproval.objects.create(
            company=project.company,
            project=project,
            entity_type="PROJECT",
            entity_id=str(project.id),
            action="ACTIVATED",
            actor=user,
            comment=comment or "Project registration approved & activated",
        )
        log_project_audit(
            project=project,
            actor=user,
            action="PROJECT_ACTIVATED",
            entity_type="Project",
            entity_id=str(project.id),
            previous_state={"status": prev},
            new_state={"status": project.status, "approved_contract_value": str(project.approved_contract_value), "budget_amount": str(project.budget_amount)},
        )
        return project

    @staticmethod
    @transaction.atomic
    def provision_site_controls(site: Site) -> Site:
        """Auto-provision dedicated site store, petty-cash account, and cost center when absent."""
        project = site.project
        company = project.company
        suffix = f"{project.code}-{site.code}".replace(" ", "")
        changed = []

        if not site.site_store_id:
            wh_code = f"ST-{suffix}"[:32]
            wh, _ = Warehouse.objects.get_or_create(
                company=company,
                code=wh_code,
                defaults={
                    "name": f"{site.name} Site Store"[:160],
                    "store_kind": Warehouse.StoreKind.SITE_STORE,
                    "project": project,
                    "site": site,
                },
            )
            site.site_store = wh
            changed.append("site_store")

        if not site.site_cost_center_id:
            cc_code = f"CC-{suffix}"[:24]
            cc, _ = CostCenter.objects.get_or_create(
                company=company,
                code=cc_code,
                defaults={
                    "name": f"{site.name} Cost Center"[:150],
                    "project": project,
                    "site": site,
                },
            )
            site.site_cost_center = cc
            changed.append("site_cost_center")

        if not site.site_cash_account_id:
            ca_code = f"SC-{suffix}"[:32]
            ca = CashAccount.objects.filter(company=company, code=ca_code).first()
            if not ca:
                gl_code = f"101-{suffix[:14]}"[:20]
                if Account.objects.filter(company=company, code=gl_code).exists():
                    gl_code = f"101{str(site.id)[:8].upper()}"
                gl_acc, _ = Account.objects.get_or_create(
                    company=company,
                    code=gl_code,
                    defaults={
                        "name": f"{site.name} Site Petty Cash"[:180],
                        "account_type": Account.AccountType.ASSET,
                        "control_role": Account.ControlRole.CASH,
                        "allow_direct_posting": True,
                    },
                )
                ca = CashAccount.objects.create(
                    company=company,
                    project=project,
                    site=site,
                    code=ca_code,
                    name=f"{site.name} Site Cash"[:150],
                    cash_type=CashAccount.CashType.SITE,
                    currency=project.currency or "NPR",
                    gl_account=gl_acc,
                )
            site.site_cash_account = ca
            changed.append("site_cash_account")

        if changed:
            site.save(update_fields=changed)
        return site

