from collections import defaultdict
from datetime import date, timedelta
from decimal import Decimal
from zoneinfo import ZoneInfo

from django.core.cache import cache
from django.db.models import Count, Q, Sum
from django.utils import timezone

from apps.accounting.models import Account, LedgerEntry, Voucher
from apps.accounting.serializers import VoucherSerializer
from apps.accounting.services import ReportingService
from apps.accounts_rbac.constants import Permissions
from apps.accounts_rbac.models import Device
from apps.accounts_rbac.policies import scope_queryset
from apps.audit.models import AuditEvent
from apps.localization.bs_calendar import ad_to_bs
from apps.projects.models import CostCode, Project, Site
from apps.sync.models import SyncOperation
from apps.tenancy.models import Branch, FiscalPeriod, FiscalYear
from .cache import build_cache_key
from .models import DEFAULT_VISIBLE_KPIS, DEFAULT_WIDGET_LAYOUT, DashboardPreference


HIGH_VALUE_THRESHOLD = Decimal("200000.00")
OVERDUE_APPROVAL_DAYS = 3


def _parse_filters(company, params: dict) -> dict:
    fy_id = params.get("fiscal_year")
    branch_id = params.get("branch")
    project_id = params.get("project")
    df_raw = params.get("date_from")
    dt_raw = params.get("date_to")
    range_preset = params.get("range", "fy")

    fy = None
    if fy_id:
        fy = FiscalYear.objects.filter(company=company, id=fy_id).first()
    if not fy:
        fy = FiscalYear.objects.filter(company=company, is_current=True).first()

    today = timezone.localdate()
    date_from = date.fromisoformat(df_raw) if df_raw else None
    date_to = date.fromisoformat(dt_raw) if dt_raw else None

    if not date_from and not date_to:
        if range_preset == "30d":
            date_from = today - timedelta(days=30)
            date_to = today
        elif range_preset == "month":
            date_from = today.replace(day=1)
            date_to = today
        elif range_preset == "quarter":
            date_from = today - timedelta(days=90)
            date_to = today
        elif fy:
            date_from = fy.start_date
            date_to = fy.end_date

    return {
        "fiscal_year": fy,
        "branch_id": branch_id or None,
        "project_id": project_id or None,
        "date_from": date_from,
        "date_to": date_to,
        "range": range_preset,
    }


def _filtered_entries(company, filters: dict):
    qs = LedgerEntry.objects.select_related("account", "project", "cost_code").filter(company=company)
    if filters["date_from"]:
        qs = qs.filter(posting_date__gte=filters["date_from"])
    if filters["date_to"]:
        qs = qs.filter(posting_date__lte=filters["date_to"])
    if filters["branch_id"]:
        qs = qs.filter(branch_id=filters["branch_id"])
    if filters["project_id"]:
        qs = qs.filter(project_id=filters["project_id"])
    return qs


class DashboardService:
    @staticmethod
    def get_greeting(*, user, company, branch_id: str | None = None) -> dict:
        tz = ZoneInfo("Asia/Kathmandu")
        now_local = timezone.now().astimezone(tz)
        hour = now_local.hour
        if 5 <= hour < 12:
            salutation = "Good Morning"
        elif 12 <= hour < 17:
            salutation = "Good Afternoon"
        elif 17 <= hour < 21:
            salutation = "Good Evening"
        else:
            salutation = "Good Night"

        first_name = (user.full_name or user.first_name or user.username).split()[0]
        bs_today = ad_to_bs(now_local.date())
        fy = FiscalYear.objects.filter(company=company, is_current=True).first()
        branch = (
            Branch.objects.filter(company=company, id=branch_id).first()
            if branch_id
            else Branch.objects.filter(company=company, is_head_office=True).first()
        )
        last_login_ev = (
            AuditEvent.objects.filter(actor=user, action="AUTH_LOGIN")
            .order_by("-created_at")
            .first()
        )
        last_sync_op = (
            SyncOperation.objects.filter(company=company, status=SyncOperation.Status.APPLIED)
            .order_by("-created_at")
            .first()
        )
        pref = DashboardPreference.objects.filter(user=user, company=company).first()

        return {
            "salutation": salutation,
            "first_name": first_name,
            "full_name": user.full_name or user.username,
            "custom_welcome_message": (
                pref.custom_welcome_message
                if pref and pref.custom_welcome_message
                else "Welcome back. Here is your company's live financial & project overview."
            ),
            "timezone": "Asia/Kathmandu",
            "server_iso": now_local.isoformat(),
            "ad_date": now_local.date().isoformat(),
            "ad_display": now_local.strftime("%A · %d %B %Y").upper(),
            "bs_date": bs_today.isoformat(),
            "bs_display": bs_today.display(),
            "company": {
                "id": str(company.id),
                "code": company.code,
                "name": company.name,
                "currency": company.base_currency,
                "calendar_preference": company.calendar_preference,
            },
            "branch": {"id": str(branch.id), "code": branch.code, "name": branch.name} if branch else None,
            "fiscal_year": {"id": str(fy.id), "name": fy.name} if fy else None,
            "last_login_at": last_login_ev.created_at.isoformat() if last_login_ev else None,
            "last_sync_at": last_sync_op.created_at.isoformat() if last_sync_op else None,
        }

    @staticmethod
    def get_summary(*, company, params: dict) -> dict:
        filters = _parse_filters(company, params)
        cache_key = build_cache_key(
            "summary",
            company.id,
            {
                "df": filters["date_from"],
                "dt": filters["date_to"],
                "br": filters["branch_id"],
                "pr": filters["project_id"],
            },
        )
        cached = cache.get(cache_key)
        if cached:
            return cached

        tb = ReportingService.get_trial_balance(
            company=company, date_to=filters["date_to"], project_id=filters["project_id"]
        )
        pl = ReportingService.get_profit_and_loss(
            company=company,
            date_from=filters["date_from"],
            date_to=filters["date_to"],
            project_id=filters["project_id"],
        )

        def net_prefix(prefixes: tuple[str, ...], normal_credit: bool = False) -> Decimal:
            total = Decimal("0.00")
            for row in tb["rows"]:
                if row["code"].startswith(prefixes):
                    d = Decimal(row["closing_debit"])
                    c = Decimal(row["closing_credit"])
                    total += (c - d) if normal_credit else (d - c)
            return total

        cash_bal = net_prefix(("1010",), False)
        bank_bal = net_prefix(("1020",), False)
        ar_bal = net_prefix(("11",), False)
        ap_bal = net_prefix(("201", "20"), True)
        tax_payable = net_prefix(("21",), True)

        total_assets = Decimal("0.00")
        total_liabilities = Decimal("0.00")
        for row in tb["rows"]:
            d = Decimal(row["closing_debit"])
            c = Decimal(row["closing_credit"])
            if row["account_type"] == Account.AccountType.ASSET:
                total_assets += d - c
            elif row["account_type"] == Account.AccountType.LIABILITY:
                total_liabilities += c - d

        working_capital = total_assets - total_liabilities

        # Previous period comparison (prior window of equal length before date_from)
        revenue_delta_pct = None
        if filters["date_from"] and filters["date_to"]:
            span = (filters["date_to"] - filters["date_from"]).days + 1
            prev_to = filters["date_from"] - timedelta(days=1)
            prev_from = prev_to - timedelta(days=max(span - 1, 1))
            prev_pl = ReportingService.get_profit_and_loss(
                company=company,
                date_from=prev_from,
                date_to=prev_to,
                project_id=filters["project_id"],
            )
            prev_rev = Decimal(prev_pl["total_income"])
            cur_rev = Decimal(pl["total_income"])
            if prev_rev > 0:
                revenue_delta_pct = float(((cur_rev - prev_rev) / prev_rev * 100).quantize(Decimal("0.1")))

        v_qs = Voucher.objects.filter(company=company)
        if filters["branch_id"]:
            v_qs = v_qs.filter(branch_id=filters["branch_id"])
        if filters["project_id"]:
            v_qs = v_qs.filter(project_id=filters["project_id"])

        pending_submitted = v_qs.filter(status=Voucher.Status.SUBMITTED).count()
        pending_approved = v_qs.filter(status=Voucher.Status.APPROVED).count()
        outstanding_sales_cnt = v_qs.filter(
            voucher_type=Voucher.VoucherType.SALES, status=Voucher.Status.POSTED
        ).count()
        outstanding_purchase_cnt = v_qs.filter(
            voucher_type=Voucher.VoucherType.PURCHASE, status=Voucher.Status.POSTED
        ).count()

        projects = Project.objects.filter(company=company)
        total_projects = projects.count()
        active_sites = Site.objects.filter(project__company=company, is_active=True).count()
        over_budget_count = 0
        for p in projects:
            agg = LedgerEntry.objects.filter(
                company=company, project=p, account__account_type=Account.AccountType.EXPENSE
            ).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
            actual = (agg["d"] or Decimal("0.00")) - (agg["c"] or Decimal("0.00"))
            if p.budget_amount > 0 and actual > p.budget_amount:
                over_budget_count += 1

        revenue_dec = Decimal(pl["total_income"])
        net_profit_dec = Decimal(pl["net_profit"])
        margin_pct = (
            float((net_profit_dec / revenue_dec * 100).quantize(Decimal("0.1")))
            if revenue_dec > 0
            else 0.0
        )

        result = {
            "refreshed_at": timezone.now().isoformat(),
            "currency": company.base_currency,
            "kpis": {
                "cash": {"value": str(cash_bal), "subtitle": "Cash in Hand (1010*)"},
                "bank": {"value": str(bank_bal), "subtitle": "Bank Accounts (1020*)"},
                "receivable": {
                    "value": str(ar_bal),
                    "subtitle": f"{outstanding_sales_cnt} posted sales vouchers",
                },
                "payable": {
                    "value": str(ap_bal),
                    "subtitle": f"{outstanding_purchase_cnt} posted purchase vouchers",
                },
                "total_revenue": {
                    "value": pl["total_income"],
                    "delta_pct": revenue_delta_pct,
                    "subtitle": "Posted contract & sales income",
                },
                "total_expenses": {
                    "value": pl["total_expense"],
                    "subtitle": "Period-to-date expenses",
                },
                "net_profit": {
                    "value": pl["net_profit"],
                    "margin_pct": margin_pct,
                    "subtitle": f"{margin_pct}% of revenue",
                },
                "pending_vouchers": {
                    "value": str(pending_submitted + pending_approved),
                    "awaiting_approval": pending_submitted,
                    "awaiting_posting": pending_approved,
                    "subtitle": f"{pending_submitted} awaiting approval · {pending_approved} ready to post",
                },
                "total_assets": {"value": str(total_assets), "subtitle": "Authoritative asset balances"},
                "total_liabilities": {"value": str(total_liabilities), "subtitle": "Authoritative liability balances"},
                "working_capital": {"value": str(working_capital), "subtitle": "Assets minus Liabilities"},
                "tax_payable": {"value": str(tax_payable), "subtitle": "VAT & TDS control balances"},
                "total_projects": {"value": str(total_projects), "subtitle": "Registered company projects"},
                "active_sites": {"value": str(active_sites), "subtitle": "Operational construction sites"},
                "projects_over_budget": {
                    "value": str(over_budget_count),
                    "subtitle": "Actual expense > approved budget",
                },
            },
            "modules_status": {
                "accounting": True,
                "projects": True,
                "sync": True,
                "banking_cash": True,
                "bank_reconciliation": True,
                "multi_currency": company.multi_currency_enabled,
                "loans_bg": True,
                "ap_ar_subledger": False,
                "payroll": False,
                "inventory": False,
            },
        }
        cache.set(cache_key, result, timeout=60)
        return result

    @staticmethod
    def get_quick_actions(*, permissions: list[str], is_superuser: bool) -> dict:
        def allowed(perm: str | None) -> bool:
            return is_superuser or perm is None or perm in permissions

        voucher_tiles = [
            {"id": "PAYMENT", "label": "Payment", "subtitle": "Payment Voucher (F5)", "shortcut": "F5", "voucher_type": "PAYMENT", "module_enabled": True, "allowed": allowed(Permissions.VOUCHER_CREATE)},
            {"id": "RECEIPT", "label": "Receipt", "subtitle": "Receipt Voucher (F6)", "shortcut": "F6", "voucher_type": "RECEIPT", "module_enabled": True, "allowed": allowed(Permissions.VOUCHER_CREATE)},
            {"id": "JOURNAL", "label": "Journal", "subtitle": "Journal Voucher (F7)", "shortcut": "F7", "voucher_type": "JOURNAL", "module_enabled": True, "allowed": allowed(Permissions.VOUCHER_CREATE)},
            {"id": "CONTRA", "label": "Contra", "subtitle": "Bank Transfer (F4)", "shortcut": "F4", "voucher_type": "CONTRA", "module_enabled": True, "allowed": allowed(Permissions.VOUCHER_CREATE)},
            {"id": "PURCHASE", "label": "Purchase", "subtitle": "Purchase Voucher (F9)", "shortcut": "F9", "voucher_type": "PURCHASE", "module_enabled": True, "allowed": allowed(Permissions.VOUCHER_CREATE)},
            {"id": "SALES", "label": "Sales", "subtitle": "Sales Invoice (F8)", "shortcut": "F8", "voucher_type": "SALES", "module_enabled": True, "allowed": allowed(Permissions.VOUCHER_CREATE)},
        ]
        extended_tiles = [
            {"id": "PROJECT_EXPENSE", "label": "Project Expense", "subtitle": "Site/project voucher", "voucher_type": "PAYMENT", "module_enabled": True, "allowed": allowed(Permissions.VOUCHER_CREATE)},
            {"id": "CREDIT_NOTE", "label": "Credit Note", "subtitle": "Sales adjustment", "voucher_type": "CREDIT_NOTE", "module_enabled": True, "allowed": allowed(Permissions.VOUCHER_CREATE)},
            {"id": "DEBIT_NOTE", "label": "Debit Note", "subtitle": "Purchase adjustment", "voucher_type": "DEBIT_NOTE", "module_enabled": True, "allowed": allowed(Permissions.VOUCHER_CREATE)},
            {"id": "COA", "label": "Chart of Accounts", "subtitle": "Ledgers & NFRS map", "target_section": "coa", "module_enabled": True, "allowed": allowed(Permissions.COA_READ)},
            {"id": "TRIAL_BALANCE", "label": "Trial Balance", "subtitle": "Dr/Cr reconciliation", "target_section": "reports", "module_enabled": True, "allowed": allowed(Permissions.REPORT_READ)},
            {"id": "SYNC", "label": "Device Sync", "subtitle": "Offline outbox queue", "target_section": "sync", "module_enabled": True, "allowed": allowed(Permissions.SYNC_PULL)},
            {"id": "PAYROLL", "label": "Payroll", "subtitle": "Phase 4 module", "module_enabled": False, "allowed": allowed(Permissions.REPORT_READ)},
            {"id": "TIMESHEET", "label": "Timesheet", "subtitle": "Phase 4 module", "module_enabled": False, "allowed": allowed(Permissions.PROJECT_READ)},
            {"id": "STOCK_JOURNAL", "label": "Stock Journal", "subtitle": "Phase 3/4 module", "module_enabled": False, "allowed": allowed(Permissions.PROJECT_READ)},
            {"id": "BANK_REC", "label": "Bank Reconciliation", "subtitle": "Match bank statements", "target_section": "banking:reconciliation", "module_enabled": True, "allowed": allowed(Permissions.BANKING_READ)},
        ]
        return {"voucher_tiles": voucher_tiles, "extended_tiles": extended_tiles}

    @staticmethod
    def get_pending_vouchers(*, company, user, params: dict, membership=None) -> dict:
        qs = (
            Voucher.objects.select_related("project", "branch", "created_by")
            .prefetch_related("lines__account")
            .filter(
                company=company,
                status__in=[Voucher.Status.SUBMITTED, Voucher.Status.APPROVED],
            )
            .order_by("voucher_date", "created_at")
        )
        if membership:
            qs = scope_queryset(qs, membership, user)
        if params.get("branch"):
            qs = qs.filter(branch_id=params["branch"])
        if params.get("project"):
            qs = qs.filter(project_id=params["project"])

        by_type = defaultdict(lambda: {"count": 0, "amount": Decimal("0.00"), "awaiting_approval": 0, "awaiting_posting": 0})
        items = []
        total_value = Decimal("0.00")
        overdue_cutoff = timezone.now() - timedelta(days=OVERDUE_APPROVAL_DAYS)
        overdue_count = 0
        high_value_count = 0

        for v in qs[:50]:
            amt = sum((l.debit for l in v.lines.all()), Decimal("0.00"))
            total_value += amt
            bucket = by_type[v.voucher_type]
            bucket["count"] += 1
            bucket["amount"] += amt
            if v.status == Voucher.Status.SUBMITTED:
                bucket["awaiting_approval"] += 1
            else:
                bucket["awaiting_posting"] += 1

            is_overdue = v.created_at < overdue_cutoff
            is_high_value = amt >= HIGH_VALUE_THRESHOLD
            if is_overdue:
                overdue_count += 1
            if is_high_value:
                high_value_count += 1

            items.append(
                {
                    "id": str(v.id),
                    "voucher_no": v.voucher_no or f"DRAFT-{str(v.id)[:6].upper()}",
                    "voucher_type": v.voucher_type,
                    "voucher_date": v.voucher_date.isoformat(),
                    "bs_date": v.bs_date,
                    "status": v.status,
                    "amount": str(amt),
                    "project_code": v.project.code if v.project else "HO",
                    "branch_name": v.branch.name if v.branch else "Head Office",
                    "party_name": v.party_name,
                    "narration": v.narration,
                    "created_by_id": str(v.created_by_id),
                    "created_by_name": v.created_by.full_name or v.created_by.username,
                    "can_self_approve": (v.created_by_id != user.id) or user.is_superuser,
                    "is_overdue": is_overdue,
                    "is_high_value": is_high_value,
                }
            )

        return {
            "total_pending": len(items),
            "total_value": str(total_value),
            "overdue_count": overdue_count,
            "high_value_count": high_value_count,
            "by_type": [
                {
                    "voucher_type": vt,
                    "count": info["count"],
                    "amount": str(info["amount"]),
                    "awaiting_approval": info["awaiting_approval"],
                    "awaiting_posting": info["awaiting_posting"],
                }
                for vt, info in by_type.items()
            ],
            "items": items,
        }

    @staticmethod
    def get_recent_transactions(*, company, params: dict, user=None, membership=None) -> dict:
        qs = (
            Voucher.objects.select_related("project", "branch", "created_by", "approved_by", "posted_by")
            .prefetch_related("lines__account")
            .filter(company=company)
        )
        if membership and user:
            qs = scope_queryset(qs, membership, user)
        if params.get("search"):
            s = params["search"].strip()
            qs = qs.filter(
                Q(voucher_no__icontains=s) | Q(narration__icontains=s) | Q(party_name__icontains=s)
            )
        if params.get("voucher_type"):
            qs = qs.filter(voucher_type=params["voucher_type"])
        if params.get("status"):
            qs = qs.filter(status=params["status"])
        if params.get("project"):
            qs = qs.filter(project_id=params["project"])
        if params.get("branch"):
            qs = qs.filter(branch_id=params["branch"])
        if params.get("date_from"):
            qs = qs.filter(voucher_date__gte=date.fromisoformat(params["date_from"]))
        if params.get("date_to"):
            qs = qs.filter(voucher_date__lte=date.fromisoformat(params["date_to"]))

        vouchers = list(qs[:25])
        return {"count": len(vouchers), "results": VoucherSerializer(vouchers, many=True).data}

    @staticmethod
    def get_financial_analytics(*, company, params: dict) -> dict:
        filters = _parse_filters(company, params)
        cache_key = build_cache_key(
            "analytics",
            company.id,
            {
                "df": filters["date_from"],
                "dt": filters["date_to"],
                "br": filters["branch_id"],
                "pr": filters["project_id"],
            },
        )
        cached = cache.get(cache_key)
        if cached:
            return cached

        entries = _filtered_entries(company, filters)

        monthly: dict[str, dict[str, Decimal]] = defaultdict(
            lambda: {
                "revenue": Decimal("0.00"),
                "expenses": Decimal("0.00"),
                "cash_inflow": Decimal("0.00"),
                "cash_outflow": Decimal("0.00"),
            }
        )
        expense_by_category: dict[str, Decimal] = defaultdict(lambda: Decimal("0.00"))

        for e in entries:
            month_key = e.posting_date.strftime("%Y-%m")
            atype = e.account.account_type
            if atype == Account.AccountType.INCOME:
                monthly[month_key]["revenue"] += e.base_credit - e.base_debit
            elif atype == Account.AccountType.EXPENSE:
                exp_amt = e.base_debit - e.base_credit
                monthly[month_key]["expenses"] += exp_amt
                cat = e.cost_code.category if e.cost_code else "OVERHEAD"
                expense_by_category[cat] += exp_amt

            if e.account.code.startswith(("1010", "1020")):
                monthly[month_key]["cash_inflow"] += e.base_debit
                monthly[month_key]["cash_outflow"] += e.base_credit

        monthly_series = []
        for mk in sorted(monthly.keys()):
            m = monthly[mk]
            rev = m["revenue"]
            exp = m["expenses"]
            inflow = m["cash_inflow"]
            outflow = m["cash_outflow"]
            monthly_series.append(
                {
                    "month": mk,
                    "label": date.fromisoformat(f"{mk}-01").strftime("%b %Y"),
                    "revenue": float(rev),
                    "expenses": float(exp),
                    "profit": float(rev - exp),
                    "cash_inflow": float(inflow),
                    "cash_outflow": float(outflow),
                    "net_cash": float(inflow - outflow),
                }
            )

        expense_distribution = [
            {"category": cat, "amount": float(amt)}
            for cat, amt in sorted(expense_by_category.items(), key=lambda x: x[1], reverse=True)
            if amt > 0
        ]

        project_perf = DashboardService.get_project_performance(company=company, params=params)

        result = {
            "monthly_series": monthly_series,
            "expense_distribution": expense_distribution,
            "project_budget_vs_actual": [
                {
                    "code": p["code"],
                    "name": p["name"],
                    "budget": float(Decimal(p["budget_amount"])),
                    "actual": float(Decimal(p["actual_cost"])),
                    "overrun": p["is_over_budget"],
                }
                for p in project_perf["projects"]
            ],
        }
        cache.set(cache_key, result, timeout=60)
        return result

    @staticmethod
    def get_project_performance(*, company, params: dict, user=None, membership=None) -> dict:
        projects = Project.objects.prefetch_related("sites").filter(company=company)
        if membership and user:
            projects = scope_queryset(projects, membership, user, is_project_model=True)
        if params.get("project"):
            projects = projects.filter(id=params["project"])

        rows = []
        total_contract = Decimal("0.00")
        total_budget = Decimal("0.00")
        total_actual = Decimal("0.00")

        for p in projects:
            entries = LedgerEntry.objects.select_related("account", "cost_code").filter(
                company=company, project=p
            )
            by_cat = defaultdict(lambda: Decimal("0.00"))
            actual_cost = Decimal("0.00")
            earned_revenue = Decimal("0.00")

            for e in entries:
                if e.account.account_type == Account.AccountType.EXPENSE:
                    amt = e.base_debit - e.base_credit
                    actual_cost += amt
                    cat = e.cost_code.category if e.cost_code else "OVERHEAD"
                    by_cat[cat] += amt
                elif e.account.account_type == Account.AccountType.INCOME:
                    earned_revenue += e.base_credit - e.base_debit

            remaining = p.budget_amount - actual_cost
            util_pct = (
                float((actual_cost / p.budget_amount * 100).quantize(Decimal("0.1")))
                if p.budget_amount > 0
                else 0.0
            )
            margin = earned_revenue - actual_cost
            total_contract += p.contract_amount
            total_budget += p.budget_amount
            total_actual += actual_cost

            rows.append(
                {
                    "id": str(p.id),
                    "code": p.code,
                    "name": p.name,
                    "client_name": p.client_name,
                    "location": p.location,
                    "status": p.status,
                    "site_count": p.sites.filter(is_active=True).count(),
                    "contract_amount": str(p.contract_amount),
                    "budget_amount": str(p.budget_amount),
                    "earned_revenue": str(earned_revenue),
                    "actual_cost": str(actual_cost),
                    "remaining_budget": str(remaining),
                    "utilization_pct": util_pct,
                    "is_over_budget": p.budget_amount > 0 and actual_cost > p.budget_amount,
                    "margin": str(margin),
                    "costs_by_category": {
                        "MATERIAL": str(by_cat["MATERIAL"]),
                        "LABOR": str(by_cat["LABOR"]),
                        "EQUIPMENT": str(by_cat["EQUIPMENT"]),
                        "SUBCONTRACT": str(by_cat["SUBCONTRACT"]),
                        "OVERHEAD": str(by_cat["OVERHEAD"] + by_cat["TRANSPORT"]),
                    },
                }
            )

        return {
            "totals": {
                "project_count": len(rows),
                "total_contract": str(total_contract),
                "total_budget": str(total_budget),
                "total_actual": str(total_actual),
                "total_remaining": str(total_budget - total_actual),
            },
            "projects": rows,
        }

    @staticmethod
    def get_aging(*, company) -> dict:
        """
        Provisional AP/AR aging derived from posted SALES/PURCHASE vouchers by age in days,
        plus authoritative control-account balances (11* AR, 201* AP).
        """
        today = timezone.localdate()

        def bucketize(voucher_type: str, control_prefixes: tuple[str, ...]) -> dict:
            tb = ReportingService.get_trial_balance(company=company)
            control_bal = Decimal("0.00")
            is_credit_normal = voucher_type == Voucher.VoucherType.PURCHASE
            for r in tb["rows"]:
                if r["code"].startswith(control_prefixes):
                    d = Decimal(r["closing_debit"])
                    c = Decimal(r["closing_credit"])
                    control_bal += (c - d) if is_credit_normal else (d - c)

            buckets = {"0_30": Decimal("0.00"), "31_60": Decimal("0.00"), "61_90": Decimal("0.00"), "90_plus": Decimal("0.00")}
            vouchers = Voucher.objects.prefetch_related("lines").filter(
                company=company, voucher_type=voucher_type, status=Voucher.Status.POSTED
            )
            voucher_rows = []
            for v in vouchers[:20]:
                amt = sum((l.debit for l in v.lines.all()), Decimal("0.00"))
                age = max((today - v.voucher_date).days, 0)
                if age <= 30:
                    buckets["0_30"] += amt
                elif age <= 60:
                    buckets["31_60"] += amt
                elif age <= 90:
                    buckets["61_90"] += amt
                else:
                    buckets["90_plus"] += amt
                voucher_rows.append(
                    {
                        "id": str(v.id),
                        "voucher_no": v.voucher_no,
                        "party_name": v.party_name or "Unnamed Party",
                        "voucher_date": v.voucher_date.isoformat(),
                        "age_days": age,
                        "amount": str(amt),
                    }
                )

            voucher_sum = sum(buckets.values(), Decimal("0.00"))
            # Include opening/unallocated control balance in 0_30 when no itemised invoice sub-ledger exists yet
            if control_bal > voucher_sum:
                buckets["0_30"] += control_bal - voucher_sum
            denom = max(sum(buckets.values(), Decimal("0.00")), Decimal("1.00"))
            return {
                "total_outstanding": str(control_bal),
                "source_note": "Derived from posted control accounts & vouchers (provisional until Invoice sub-ledger)",
                "buckets": [
                    {"label": "0–30 days", "amount": str(buckets["0_30"]), "pct": round(float(buckets["0_30"] / denom * 100), 1)},
                    {"label": "31–60 days", "amount": str(buckets["31_60"]), "pct": round(float(buckets["31_60"] / denom * 100), 1)},
                    {"label": "61–90 days", "amount": str(buckets["61_90"]), "pct": round(float(buckets["61_90"] / denom * 100), 1)},
                    {"label": "90+ days", "amount": str(buckets["90_plus"]), "pct": round(float(buckets["90_plus"] / denom * 100), 1)},
                ],
                "items": voucher_rows,
            }

        return {
            "receivables": bucketize(Voucher.VoucherType.SALES, ("11",)),
            "payables": bucketize(Voucher.VoucherType.PURCHASE, ("201",)),
        }

    @staticmethod
    def get_alerts(*, company) -> dict:
        alerts = []
        perf = DashboardService.get_project_performance(company=company, params={})
        for p in perf["projects"]:
            if p["is_over_budget"]:
                alerts.append(
                    {
                        "id": f"overrun-{p['id']}",
                        "severity": "critical",
                        "category": "Budget Overrun",
                        "title": f"{p['code']} exceeded approved budget ({p['utilization_pct']}%)",
                        "detail": f"Actual {p['actual_cost']} vs Budget {p['budget_amount']}",
                    }
                )
            elif p["utilization_pct"] >= 85:
                alerts.append(
                    {
                        "id": f"near-{p['id']}",
                        "severity": "warning",
                        "category": "Budget Threshold",
                        "title": f"{p['code']} at {p['utilization_pct']}% budget utilization",
                        "detail": f"Remaining budget: {p['remaining_budget']}",
                    }
                )

        overdue_cutoff = timezone.now() - timedelta(days=OVERDUE_APPROVAL_DAYS)
        overdue_vouchers = Voucher.objects.filter(
            company=company,
            status=Voucher.Status.SUBMITTED,
            created_at__lt=overdue_cutoff,
        ).count()
        if overdue_vouchers:
            alerts.append(
                {
                    "id": "overdue-approvals",
                    "severity": "warning",
                    "category": "Approval SLA",
                    "title": f"{overdue_vouchers} voucher(s) pending approval > {OVERDUE_APPROVAL_DAYS} days",
                    "detail": "Review in Pending Approval Center.",
                }
            )

        locked_periods = FiscalPeriod.objects.filter(
            fiscal_year__company=company, status=FiscalPeriod.Status.LOCKED
        ).count()
        if locked_periods:
            alerts.append(
                {
                    "id": "locked-periods",
                    "severity": "info",
                    "category": "Period Control",
                    "title": f"{locked_periods} fiscal period(s) currently locked",
                    "detail": "Posting into locked periods is blocked.",
                }
            )

        failed_syncs = SyncOperation.objects.filter(
            company=company, status=SyncOperation.Status.REJECTED
        ).count()
        if failed_syncs:
            alerts.append(
                {
                    "id": "sync-rejects",
                    "severity": "warning",
                    "category": "Device Sync",
                    "title": f"{failed_syncs} rejected offline sync operation(s)",
                    "detail": "Check Sync Center for details.",
                }
            )

        return {"count": len(alerts), "alerts": alerts}

    @staticmethod
    def get_activity(*, company, user) -> dict:
        events = AuditEvent.objects.select_related("actor").filter(company=company)[:15]
        devices = Device.objects.filter(company=company, user=user)
        recent_ops = SyncOperation.objects.filter(company=company)[:10]
        return {
            "audit_events": [
                {
                    "id": str(e.id),
                    "action": e.action,
                    "entity_type": e.entity_type,
                    "entity_id": e.entity_id,
                    "actor": e.actor.username if e.actor else "system",
                    "device_id": e.device_id,
                    "new_state": e.new_state,
                    "created_at": e.created_at.isoformat(),
                }
                for e in events
            ],
            "sync_status": {
                "active_devices": devices.filter(status=Device.Status.ACTIVE).count(),
                "revoked_devices": devices.filter(status=Device.Status.REVOKED).count(),
                "recent_operations": [
                    {
                        "operation_id": o.operation_id,
                        "entity_type": o.entity_type,
                        "status": o.status,
                        "created_at": o.created_at.isoformat(),
                    }
                    for o in recent_ops
                ],
            },
        }

    @staticmethod
    def get_reports_overview(*, company) -> dict:
        tb = ReportingService.get_trial_balance(company=company)
        pl = ReportingService.get_profit_and_loss(company=company)
        bs = ReportingService.get_balance_sheet(company=company)
        return {
            "trial_balance_balanced": tb["is_balanced"],
            "trial_balance_total": tb["total_debit"],
            "net_profit": pl["net_profit"],
            "total_assets": bs["total_assets"],
            "balance_sheet_balanced": bs["is_balanced"],
            "account_count": Account.objects.filter(company=company, is_active=True).count(),
            "cost_code_count": CostCode.objects.filter(company=company, is_active=True).count(),
        }

    @staticmethod
    def get_treasury_overview(*, company) -> dict:
        from apps.banking.models import BankAccount, BankStatementLine, CashAccount, ChequeLeaf
        from apps.banking.services import BankingService
        from apps.loans.models import BankFacility, BankGuarantee, LoanCollateral, LoanScheduleInstallment
        from apps.loans.services import LoanService

        today = timezone.localdate()
        bank_accounts = BankAccount.objects.select_related("bank_branch__bank", "gl_account").filter(
            company=company, status=BankAccount.Status.ACTIVE
        )
        bank_rows = []
        total_bank_npr = Decimal("0.00")
        fx_exposure = defaultdict(lambda: Decimal("0.00"))
        for ba in bank_accounts:
            bal = BankingService.get_gl_balance(ba.gl_account)
            total_bank_npr += bal
            if ba.currency != company.base_currency:
                fx_exposure[ba.currency] += bal
            bank_rows.append(
                {
                    "id": str(ba.id),
                    "name": ba.account_name,
                    "bank": ba.bank_branch.bank.short_code,
                    "masked": ba.account_number_masked,
                    "currency": ba.currency,
                    "balance": str(bal),
                }
            )

        cash_accounts = CashAccount.objects.select_related("gl_account").filter(
            company=company, is_active=True
        )
        cash_rows = []
        total_cash = Decimal("0.00")
        for ca in cash_accounts:
            bal = BankingService.get_gl_balance(ca.gl_account)
            total_cash += bal
            cash_rows.append({"id": str(ca.id), "code": ca.code, "name": ca.name, "cash_type": ca.cash_type, "balance": str(bal)})

        facilities = BankFacility.objects.filter(company=company).exclude(status=BankFacility.Status.CLOSED)
        total_loan_out = Decimal("0.00")
        od_cc_limit = Decimal("0.00")
        od_cc_used = Decimal("0.00")
        maturity_calendar = []
        for fac in facilities:
            out = LoanService.get_outstanding_principal(fac)
            total_loan_out += out
            if fac.facility_type in (BankFacility.FacilityType.OVERDRAFT, BankFacility.FacilityType.CASH_CREDIT):
                od_cc_limit += fac.sanctioned_limit
                od_cc_used += out
            maturity_calendar.append(
                {
                    "id": str(fac.id),
                    "code": fac.facility_code,
                    "name": fac.facility_name,
                    "type": fac.facility_type,
                    "maturity_date": fac.maturity_date.isoformat(),
                    "outstanding": str(out),
                    "limit": str(fac.sanctioned_limit),
                }
            )

        upcoming_inst = LoanScheduleInstallment.objects.filter(
            facility__company=company,
            status__in=[LoanScheduleInstallment.Status.PENDING, LoanScheduleInstallment.Status.PARTIAL],
            due_date__gte=today,
        ).order_by("due_date")[:6]
        overdue_loans = LoanScheduleInstallment.objects.filter(
            facility__company=company,
            status__in=[LoanScheduleInstallment.Status.PENDING, LoanScheduleInstallment.Status.PARTIAL, LoanScheduleInstallment.Status.OVERDUE],
            due_date__lt=today,
        ).count()

        unmatched_stmt = BankStatementLine.objects.filter(
            company=company, match_status=BankStatementLine.MatchStatus.UNMATCHED
        ).count()
        outstanding_cheques = ChequeLeaf.objects.filter(
            company=company, status__in=[ChequeLeaf.Status.ISSUED, ChequeLeaf.Status.IN_HAND]
        ).count()

        active_bgs = BankGuarantee.objects.filter(
            company=company, status__in=[BankGuarantee.Status.ACTIVE, BankGuarantee.Status.EXTENDED]
        )
        bg_exposure = sum((b.amount for b in active_bgs), Decimal("0.00"))
        collateral_total = (
            LoanCollateral.objects.filter(company=company, is_released=False).aggregate(v=Sum("assessed_value"))["v"]
            or Decimal("0.00")
        )

        int_exp_agg = LedgerEntry.objects.filter(
            company=company, account__code__startswith="53"
        ).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
        interest_expense = (int_exp_agg["d"] or Decimal("0.00")) - (int_exp_agg["c"] or Decimal("0.00"))

        return {
            "consolidated_bank": str(total_bank_npr),
            "consolidated_cash": str(total_cash),
            "bank_accounts": bank_rows,
            "cash_accounts": cash_rows,
            "fx_exposure": [{"currency": k, "amount": str(v)} for k, v in fx_exposure.items()],
            "loan_outstanding": str(total_loan_out),
            "od_cc_limit": str(od_cc_limit),
            "od_cc_used": str(od_cc_used),
            "interest_expense": str(interest_expense),
            "overdue_installments": overdue_loans,
            "unmatched_bank_lines": unmatched_stmt,
            "outstanding_cheques": outstanding_cheques,
            "guarantee_exposure": str(bg_exposure),
            "collateral_coverage": str(collateral_total),
            "upcoming_installments": [
                {
                    "facility_code": i.facility.facility_code,
                    "due_date": i.due_date.isoformat(),
                    "principal_due": str(i.principal_due),
                    "interest_due": str(i.interest_due),
                }
                for i in upcoming_inst
            ],
            "maturity_calendar": sorted(maturity_calendar, key=lambda x: x["maturity_date"])[:6],
        }

    @staticmethod
    def get_or_create_preferences(*, user, company) -> DashboardPreference:
        pref, _ = DashboardPreference.objects.get_or_create(
            user=user,
            company=company,
            defaults={"layout": DEFAULT_WIDGET_LAYOUT, "visible_kpis": DEFAULT_VISIBLE_KPIS},
        )
        return pref

    @staticmethod
    def get_operations_overview(*, company, permissions: set[str], is_superuser: bool = False) -> dict:
        out: dict = {}
        if is_superuser or Permissions.PROCUREMENT_READ in permissions:
            from apps.procurement.models import PurchaseOrder, PurchaseRequisition, ThreeWayMatch
            out["procurement"] = {
                "pending_requisitions": PurchaseRequisition.objects.filter(company=company, status="DRAFT").count(),
                "open_purchase_orders": PurchaseOrder.objects.filter(company=company, status__in=["APPROVED", "PARTIAL"]).count(),
                "po_committed_value": str(PurchaseOrder.objects.filter(company=company, status__in=["APPROVED", "PARTIAL"]).aggregate(s=Sum("total_amount"))["s"] or Decimal("0.00")),
                "matched_invoices": ThreeWayMatch.objects.filter(company=company, status=ThreeWayMatch.Status.MATCHED_POSTED).count(),
            }
        if is_superuser or Permissions.INVENTORY_READ in permissions:
            from apps.inventory.valuation import InventoryValuationService
            from apps.inventory.models import MaterialIssue
            val = InventoryValuationService.get_valuation_report(company)
            out["inventory"] = {
                "total_stock_value": str(sum((Decimal(r["total_value"]) for r in val), Decimal("0.00"))),
                "low_stock_items": sum(1 for r in val if r["is_low_stock"]),
                "material_issues_count": MaterialIssue.objects.filter(company=company, status="APPROVED").count(),
            }
        if is_superuser or Permissions.HR_READ in permissions:
            from apps.accounting.models import AdvanceRecord, EmployeeProfile
            from apps.hr.models import AttendanceRecord, PayrollRun
            today = timezone.localdate()
            out["hr"] = {
                "total_employees": EmployeeProfile.objects.filter(company=company, is_active=True).count(),
                "today_present": AttendanceRecord.objects.filter(company=company, attendance_date=today, status="PRESENT").count(),
                "advance_outstanding": str(sum((a.remaining_amount for a in AdvanceRecord.objects.filter(company=company, status__in=["OPEN", "PARTIALLY_ADJUSTED"])), Decimal("0.00"))),
                "payroll_posted": str(PayrollRun.objects.filter(company=company, status="POSTED").aggregate(s=Sum("total_net_pay"))["s"] or Decimal("0.00")) if (is_superuser or Permissions.HR_PAYROLL_SENSITIVE in permissions) else "***",
            }
        if is_superuser or Permissions.BUDGET_READ in permissions:
            from apps.budgeting.models import Budget
            from apps.budgeting.services import BudgetControlService
            eff, act, comm = Decimal("0.00"), Decimal("0.00"), Decimal("0.00")
            over_count = 0
            for b in Budget.objects.filter(company=company, status=Budget.Status.APPROVED):
                s = BudgetControlService.get_budget_summary(company, b)
                eff += Decimal(s["totals"]["effective"])
                act += Decimal(s["totals"]["actual"])
                comm += Decimal(s["totals"]["committed"])
                if Decimal(s["totals"]["available"]) < 0:
                    over_count += 1
            out["budgeting"] = {
                "approved_budget": str(eff),
                "actual_cost": str(act),
                "open_commitments": str(comm),
                "available_budget": str(eff - act - comm),
                "over_budget_count": over_count,
            }
        return out

