from decimal import Decimal, ROUND_HALF_UP
from django.db.models import Q, Sum
from django.utils import timezone

from apps.accounting.models import (
    Account,
    AdvanceRecord,
    CostCategory,
    CostCenter,
    LedgerEntry,
    Voucher,
    VoucherLineCostAllocation,
)
from apps.budgeting.models import BudgetCommitment, BudgetLine
from apps.construction_ops.models import OperationalDocument
from apps.party_hub.models import OpenItem, RABill, RetentionSchedule
from apps.projects.models import (
    Project,
    ProjectBoqLine,
    ProjectContract,
    ProjectVariationOrder,
    Site,
)
from .filter_engine import ReportFilterContext, ReportFilterEngine


Q2 = Decimal("0.01")


class ConstructionReportService:
    """
    Unified Construction Intelligence Engine:
    Strictly separates Physical Progress, Measured Value, Certified Value, Billed Value,
    Recognized GL Revenue, Accounting WIP, Committed Cost (PO/WO un-relieved), and Forecast Cost.
    """

    @staticmethod
    def build_wip_and_boq(*, company, user, membership, ctx: ReportFilterContext) -> dict:
        proj_qs = ReportFilterEngine.scope_qs(
            Project.objects.filter(company=company), user=user, membership=membership, is_project_model=True
        ).order_by("code")
        if ctx.project_id:
            proj_qs = proj_qs.filter(id=ctx.project_id)
        if ctx.search:
            proj_qs = proj_qs.filter(Q(code__icontains=ctx.search) | Q(name__icontains=ctx.search))

        project_rows = []
        boq_rows = []
        alerts = []

        for p in proj_qs:
            contract = ProjectContract.objects.filter(project=p).first()
            approved_vo = (
                ProjectVariationOrder.objects.filter(project=p, status=ProjectVariationOrder.Status.APPROVED).aggregate(
                    add=Sum("additional_value"), red=Sum("reduction_value")
                )
            )
            net_vo = (approved_vo["add"] or Decimal("0.00")) - (approved_vo["red"] or Decimal("0.00"))
            rev_contract = (contract.approved_contract_value if contract else (p.contract_amount + net_vo))

            # Approved Cost Budget (BudgetLine or Project.budget_amount)
            bgt_lines_amt = (
                BudgetLine.objects.filter(
                    budget_version__budget__company=company,
                    budget_version__budget__project=p,
                    budget_version__is_active=True,
                    budget_version__budget__status__in=["APPROVED", "LOCKED"],
                ).aggregate(s=Sum("approved_amount"))["s"]
                or Decimal("0.00")
            )
            revised_budget = bgt_lines_amt if bgt_lines_amt > 0 else (contract.approved_cost_budget if contract and contract.approved_cost_budget > 0 else p.budget_amount)

            # Accounting WIP (1400) & Posted GL Expenses & Revenue (Strictly POSTED)
            le_qs = LedgerEntry.objects.filter(company=company, project=p)
            if ctx.date_to:
                le_qs = le_qs.filter(posting_date__lte=ctx.date_to)
            wip_agg = le_qs.filter(account__control_role=Account.ControlRole.PROJECT_WIP).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
            exp_agg = le_qs.filter(account__account_type=Account.AccountType.EXPENSE).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
            rev_agg = le_qs.filter(account__account_type=Account.AccountType.INCOME).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))

            accounting_wip = (wip_agg["d"] or Decimal("0.00")) - (wip_agg["c"] or Decimal("0.00"))
            posted_exp = (exp_agg["d"] or Decimal("0.00")) - (exp_agg["c"] or Decimal("0.00"))
            recognized_revenue = (rev_agg["c"] or Decimal("0.00")) - (rev_agg["d"] or Decimal("0.00"))
            actual_project_cost = accounting_wip + posted_exp

            # Open Commitments (excludes already relieved/billed portion -> zero double counting!)
            comm_qs = BudgetCommitment.objects.filter(
                company=company, project=p, status__in=[BudgetCommitment.Status.OPEN, BudgetCommitment.Status.PARTIALLY_RELIEVED]
            )
            open_commitments = sum((max(c.committed_amount - c.relieved_amount, Decimal("0.00")) for c in comm_qs), Decimal("0.00"))

            # Billed vs Certified vs Collected
            ra_qs = RABill.objects.filter(company=company, project=p)
            work_certified = sum(
                (b.certified_gross_amount or b.current_gross_amount for b in ra_qs.filter(status__in=[
                    RABill.WorkflowStatus.CLIENT_CERTIFIED, RABill.WorkflowStatus.PARTIALLY_CERTIFIED,
                    RABill.WorkflowStatus.POSTED, RABill.WorkflowStatus.PARTIALLY_RECEIVED, RABill.WorkflowStatus.SETTLED
                ])),
                Decimal("0.00"),
            )
            work_billed = sum(
                (o.original_amount for o in OpenItem.objects.filter(
                    company=company, project=p, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=False
                ).exclude(status=OpenItem.Status.REVERSED)),
                Decimal("0.00"),
            )
            outstanding_ar = sum(
                (o.remaining_amount for o in OpenItem.objects.filter(
                    company=company, project=p, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=False
                ).exclude(status__in=[OpenItem.Status.SETTLED, OpenItem.Status.REVERSED, OpenItem.Status.WRITTEN_OFF])),
                Decimal("0.00"),
            )
            amount_collected = max(work_billed - outstanding_ar, Decimal("0.00"))
            ret_rec = sum(
                (r.remaining_retention for r in RetentionSchedule.objects.filter(
                    company=company, project=p, direction=RetentionSchedule.Direction.RECEIVABLE
                ).exclude(status=RetentionSchedule.Status.RELEASED)),
                Decimal("0.00"),
            )

            # Measured BOQ Value & Unapproved Excess Check
            measured_val = Decimal("0.00")
            boq_items = ProjectBoqLine.objects.filter(project=p).order_by("item_code")
            for bl in boq_items:
                c_qty = bl.revised_qty if bl.revised_qty > 0 else bl.contract_qty
                c_rate = bl.revised_rate if bl.revised_rate > 0 else bl.contract_rate
                measured_val += (bl.current_measured_qty * c_rate).quantize(Q2, rounding=ROUND_HALF_UP)
                excess_flag = c_qty > 0 and bl.completed_qty > c_qty and net_vo <= 0
                if excess_flag:
                    alerts.append({"project": p.code, "item_code": bl.item_code, "type": "BOQ_EXCESS_NO_VO", "detail": f"Executed {bl.completed_qty} > Contract {c_qty}"})
                boq_rows.append({
                    "project_code": p.code,
                    "project_name": p.name,
                    "boq_code": bl.item_code,
                    "description": bl.description,
                    "unit": bl.unit,
                    "contract_qty": str(c_qty),
                    "executed_qty": str(bl.completed_qty),
                    "measured_qty": str(bl.current_measured_qty),
                    "certified_qty": str(bl.previous_certified_qty),
                    "remaining_qty": str(bl.remaining_qty),
                    "contract_rate": str(c_rate),
                    "boq_value": str((c_qty * c_rate).quantize(Q2)),
                    "certified_value": str((bl.previous_certified_qty * c_rate).quantize(Q2)),
                    "unapproved_excess": excess_flag,
                })

            cost_to_complete = max(Decimal("0.00"), revised_budget - actual_project_cost - open_commitments)
            forecast_final_cost = actual_project_cost + open_commitments + cost_to_complete
            budget_variance = revised_budget - forecast_final_cost
            gross_margin = recognized_revenue - actual_project_cost
            unbilled_contract_asset = max(work_certified - work_billed, Decimal("0.00"))

            if budget_variance < 0:
                alerts.append({"project": p.code, "type": "COST_OVERRUN", "detail": f"Variance {budget_variance}"})
            if gross_margin < 0 and recognized_revenue > 0:
                alerts.append({"project": p.code, "type": "NEGATIVE_MARGIN", "detail": f"Margin {gross_margin}"})

            project_rows.append({
                "project_id": str(p.id),
                "code": p.code,
                "name": p.name,
                "contract_amount": str(p.contract_amount),
                "approved_variation": str(net_vo),
                "revised_contract_value": str(rev_contract),
                "revised_budget": str(revised_budget),
                "accounting_wip": str(accounting_wip),
                "posted_direct_cost": str(posted_exp),
                "actual_project_cost": str(actual_project_cost),
                "open_commitments": str(open_commitments),
                "cost_to_complete": str(cost_to_complete),
                "forecast_final_cost": str(forecast_final_cost),
                "budget_variance": str(budget_variance),
                "measured_work_value": str(measured_val),
                "work_certified": str(work_certified),
                "work_billed": str(work_billed),
                "recognized_revenue": str(recognized_revenue),
                "unbilled_contract_asset": str(unbilled_contract_asset),
                "amount_collected": str(amount_collected),
                "outstanding_receivable": str(outstanding_ar),
                "retention_receivable": str(ret_rec),
                "gross_margin": str(gross_margin),
            })

        return {
            "meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code="construction_wip", title="Construction WIP & BOQ Intelligence", row_count=len(project_rows)),
            "rows": project_rows,
            "projects": project_rows,
            "boq_rows": boq_rows,
            "alerts": alerts,
        }

    @staticmethod
    def build_construction_subreport(*, company, user, membership, ctx: ReportFilterContext, subreport: str) -> dict:
        if subreport in ("construction_wip", "boq_execution", "project_profitability", "contract_profitability", "cost_to_complete", "ra_billing_vs_collection", "project_cash_flow"):
            wip = ConstructionReportService.build_wip_and_boq(company=company, user=user, membership=membership, ctx=ctx)
            title_map = {
                "boq_execution": "BOQ Execution & Progress Report",
                "project_profitability": "Project Profitability Analysis",
                "contract_profitability": "Contract Profitability Summary",
                "cost_to_complete": "Cost-to-Complete & EAC Forecast",
                "ra_billing_vs_collection": "RA Billing vs Collection Statement",
                "project_cash_flow": "Project-Wise Cash Flow Summary",
            }
            wip["meta"]["report_code"] = subreport
            wip["meta"]["title"] = title_map.get(subreport, wip["meta"]["title"])
            if subreport == "boq_execution":
                wip["rows"] = wip["boq_rows"]
                wip["meta"]["row_count"] = len(wip["boq_rows"])
            return wip

        if subreport == "worksite_cost_summary":
            sites = ReportFilterEngine.scope_qs(Site.objects.select_related("project").filter(project__company=company), user=user, membership=membership, is_site_model=True)
            rows = []
            for s in sites:
                agg = LedgerEntry.objects.filter(company=company, site=s, account__account_type__in=[Account.AccountType.EXPENSE, Account.AccountType.ASSET]).filter(
                    Q(account__account_type=Account.AccountType.EXPENSE) | Q(account__control_role=Account.ControlRole.PROJECT_WIP)
                ).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
                cost = (agg["d"] or Decimal("0.00")) - (agg["c"] or Decimal("0.00"))
                rows.append({"site_id": str(s.id), "site_code": s.code, "site_name": s.name, "project_code": s.project.code, "total_cost": str(cost)})
            return {"meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code=subreport, title="Worksite Cost Summary", row_count=len(rows)), "rows": rows}

        if subreport in ("material_consumption", "labour_cost", "equipment_cost", "subcontractor_cost"):
            vtype_map = {
                "material_consumption": [Voucher.VoucherType.MATERIAL_CONSUMPTION, Voucher.VoucherType.MATERIAL_ISSUE],
                "labour_cost": [Voucher.VoucherType.LABOR_PAYMENT, Voucher.VoucherType.WAGES, Voucher.VoucherType.WAGE_ACCRUAL],
                "equipment_cost": [Voucher.VoucherType.EQUIPMENT_HIRE, Voucher.VoucherType.FUEL_EXPENSE, Voucher.VoucherType.FUEL],
                "subcontractor_cost": [Voucher.VoucherType.SUBCONTRACTOR_BILL],
            }
            title_map = {
                "material_consumption": "Material Consumption Cost Analysis",
                "labour_cost": "Labour & Daily Wages Cost Analysis",
                "equipment_cost": "Equipment & Machinery Operating Cost",
                "subcontractor_cost": "Subcontractor Cost & Certification Analysis",
            }
            qs = LedgerEntry.objects.select_related("voucher", "project", "account", "party").filter(
                company=company, voucher__voucher_type__in=vtype_map[subreport]
            ).exclude(account__account_type=Account.AccountType.INCOME)
            qs = ReportFilterEngine.scope_qs(qs, user=user, membership=membership)
            if ctx.project_id:
                qs = qs.filter(project_id=ctx.project_id)
            if ctx.date_from:
                qs = qs.filter(posting_date__gte=ctx.date_from)
            if ctx.date_to:
                qs = qs.filter(posting_date__lte=ctx.date_to)
            rows = []
            for r in qs.filter(base_debit__gt=0)[:400]:
                rows.append({
                    "posting_date": r.posting_date.isoformat(),
                    "voucher_no": r.voucher.voucher_no,
                    "project_code": r.project.code if r.project else "HO",
                    "account": f"{r.account.code} {r.account.name}",
                    "party_name": r.party.name if r.party else "-",
                    "amount": str(r.base_debit),
                    "narration": r.narration,
                })
            return {"meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code=subreport, title=title_map[subreport], row_count=len(rows)), "rows": rows}

        if subreport == "contract_variation":
            vos = ReportFilterEngine.scope_qs(ProjectVariationOrder.objects.select_related("project").filter(company=company), user=user, membership=membership, site_field=None, branch_field=None)
            rows = [{
                "variation_no": v.variation_no, "project_code": v.project.code, "title": v.title,
                "additional_value": str(v.additional_value), "reduction_value": str(v.reduction_value),
                "net_value": str(v.additional_value - v.reduction_value), "status": v.status,
            } for v in vos]
            return {"meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code=subreport, title="Contract Variation Order Report", row_count=len(rows)), "rows": rows}

        # retention_advance_report
        rets = RetentionSchedule.objects.select_related("party", "project").filter(company=company)
        advs = AdvanceRecord.objects.select_related("party", "project").filter(company=company)
        rows = [
            {"kind": f"RETENTION_{r.direction}", "party": r.party.name, "project": r.project.code if r.project else "-", "original": str(r.retention_amount), "settled": str(r.released_amount), "balance": str(r.remaining_retention), "status": r.status}
            for r in rets
        ] + [
            {"kind": a.advance_type, "party": a.party.name, "project": a.project.code if a.project else "-", "original": str(a.original_amount), "settled": str(a.adjusted_amount), "balance": str(a.remaining_amount), "status": a.status}
            for a in advs
        ]
        return {"meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code=subreport, title="Retention & Advance Consolidated Report", row_count=len(rows)), "rows": rows}


class CostCentreReportService:
    """Hierarchical Cost Centre Performance, Budget, Open Commitment & Direct+Split Reconciliation."""

    @staticmethod
    def build(*, company, user, membership, ctx: ReportFilterContext) -> dict:
        categories = list(CostCategory.objects.filter(company=company, is_active=True))
        centers_qs = ReportFilterEngine.scope_qs(
            CostCenter.objects.select_related("cost_category", "parent", "project", "site").filter(company=company, is_active=True),
            user=user,
            membership=membership,
            branch_field=None,
        )
        if ctx.project_id:
            centers_qs = centers_qs.filter(project_id=ctx.project_id)
        if ctx.cost_center_id:
            centers_qs = centers_qs.filter(id=ctx.cost_center_id)

        rows = []
        total_dr = total_cr = total_bgt = total_comm = Decimal("0.00")

        for cc in centers_qs:
            # 1. Split allocations (prevents double counting direct lines via cost_allocations__isnull=True below)
            split_qs = VoucherLineCostAllocation.objects.select_related("voucher_line").filter(
                cost_center=cc, voucher_line__voucher__company=company, voucher_line__voucher__status=Voucher.Status.POSTED
            )
            if ctx.date_from:
                split_qs = split_qs.filter(voucher_line__voucher__voucher_date__gte=ctx.date_from)
            if ctx.date_to:
                split_qs = split_qs.filter(voucher_line__voucher__voucher_date__lte=ctx.date_to)
            split_dr = split_cr = Decimal("0.00")
            for sp in split_qs:
                if sp.voucher_line.debit > 0:
                    split_dr += sp.amount
                else:
                    split_cr += sp.amount

            # 2. Direct lines without split children
            direct_qs = LedgerEntry.objects.filter(company=company, cost_center=cc, voucher_line__cost_allocations__isnull=True)
            if ctx.date_from:
                direct_qs = direct_qs.filter(posting_date__gte=ctx.date_from)
            if ctx.date_to:
                direct_qs = direct_qs.filter(posting_date__lte=ctx.date_to)
            direct_agg = direct_qs.aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
            dr = (direct_agg["d"] or Decimal("0.00")) + split_dr
            cr = (direct_agg["c"] or Decimal("0.00")) + split_cr
            actual = dr - cr

            # Budget & Open Commitments tied to CostCenter's project/cost_code
            bgt = Decimal("0.00")
            comm = Decimal("0.00")
            if cc.project_id:
                bgt = (
                    BudgetLine.objects.filter(
                        budget_version__budget__company=company,
                        budget_version__budget__project=cc.project,
                        budget_version__is_active=True,
                    ).aggregate(s=Sum("approved_amount"))["s"]
                    or Decimal("0.00")
                )
                comm = sum(
                    (max(c.committed_amount - c.relieved_amount, Decimal("0.00")) for c in BudgetCommitment.objects.filter(
                        company=company, project=cc.project, status__in=[BudgetCommitment.Status.OPEN, BudgetCommitment.Status.PARTIALLY_RELIEVED]
                    )),
                    Decimal("0.00"),
                )

            avail = bgt - actual - comm
            util_pct = str((actual * Decimal("100") / bgt).quantize(Q2)) if bgt > 0 else "0.00"
            total_dr += dr
            total_cr += cr
            total_bgt += bgt
            total_comm += comm

            rows.append({
                "id": str(cc.id),
                "code": cc.code,
                "name": cc.name,
                "category_name": cc.cost_category.name if cc.cost_category else "General",
                "parent_name": cc.parent.name if cc.parent else "",
                "project_code": cc.project.code if cc.project else "HO",
                "site_name": cc.site.name if cc.site else "",
                "budget": str(bgt),
                "actual_cost": str(actual),
                "commitments": str(comm),
                "available_budget": str(avail),
                "variance": str(bgt - actual),
                "utilization_pct": util_pct,
                "debit": str(dr),
                "credit": str(cr),
            })

        return {
            "meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code="cost_centres", title="Cost Centre Performance & Allocations", row_count=len(rows)),
            "categories": [{"id": str(c.id), "code": c.code, "name": c.name} for c in categories],
            "rows": rows,
            "summary": {"total_debit": str(total_dr), "total_credit": str(total_cr), "total_budget": str(total_bgt), "total_commitments": str(total_comm)},
        }

