# ============================================================
# ADDITIVE: Statutory Compliance & Legal Governance  (Admin / HR side)
# Mounted from hrnexus/urls.py as  path('api/', include('People.compliance_urls'))  ->  /api/compliance/...
#
#   dashboard/        Compliance Dashboard (KPI cards + Statutory Filing History & Challans)
#   pf/ esi/ pt/ tds/ PF / ESI / Professional Tax / TDS tabs
#   labour/           Labour Compliance tab (licences + inspections + status banner)
#   alerts/           Compliance Alerts tab (computed live)       meta/  dropdowns
#   registrations/    PF / ESIC / PT / TAN / LWF / Shops registration numbers (CRUD)
#   filings/          "Record Filing" - filings & challans (CRUD + record_payment / mark_filed / reopen / generate / calculate)
#   documents/        Statutory Registers & Returns Vault (CRUD, file upload/download)
#   licenses/  inspections/  reminders/  form16/   (CRUD)
#
# Auth  : AdminOrEmployeeJWTAuthentication (company admin token or employee token)
# Authz : Company Admin = everything; employee needs EmployeeRole can_<view|create|edit|delete|manage>_payroll
#         OR _employees.  Everything is company scoped.
# ============================================================
from decimal import Decimal

from django.db import transaction
from django.db.models import Count, Q, Sum
from django.http import Http404
from django.utils import timezone
from rest_framework.decorators import action
from rest_framework.parsers import FormParser, JSONParser, MultiPartParser
from rest_framework.viewsets import ViewSet

from Employee.models import Payroll

from .common import (CrudBase, emp_brief, emp_by_code, err, iso, ok, paginate, to_bool, to_date, to_decimal,
                     to_int)
from .compliance_common import (DEFAULT_DUE_DAY, MONTHS, NO_PAYMENT_TYPES, REG_FOR, ComplianceAuthMixin,
                                IsComplianceUser, active_employees, build_alerts, due_for_month, esi_members,
                                filing_defaults, filing_state, fy_months, fy_of, is_complete, last_months,
                                license_state, month_label, parse_fy, payroll_by_month, pf_members,
                                quarter_months, tds_due, uan_count)
from .compliance_models import (ComplianceDocument, ComplianceFiling, ComplianceReminder, ComplianceRegistration,
                                Form16Record, LabourInspection, LabourLicense)
from .models import Branch
from .views_vault import actor_name, check_upload, file_name, file_url, send_file

PARSERS = [JSONParser, MultiPartParser, FormParser]


def pick(value, allowed, label):
    v = str(value or "").strip().upper()
    if v not in allowed:
        raise ValueError(f"Invalid {label}. Allowed: {', '.join(allowed)}")
    return v


def branch_of(company, value):
    if value in (None, ""):
        return None
    b = Branch.objects.filter(company=company, pk=to_int(value), is_active=True).first()
    if b is None:
        raise ValueError("branch is invalid.")
    return b


def reg_of(company, value):
    if value in (None, ""):
        return None
    r = ComplianceRegistration.objects.filter(company=company, pk=to_int(value), is_active=True).first()
    if r is None:
        raise ValueError("registration is invalid.")
    return r


def money(d, key, default=None):
    v = to_decimal(d.get(key), default)
    if v is not None and v < 0:
        raise ValueError(f"{key} cannot be negative.")
    return v


def month_year(d, o=None):
    m = to_int(d.get("period_month"), getattr(o, "period_month", None))
    y = to_int(d.get("period_year"), getattr(o, "period_year", None))
    if m is not None and not 1 <= m <= 12:
        raise ValueError("period_month must be 1-12.")
    if y is not None and not 2000 <= y <= 2100:
        raise ValueError("period_year is invalid.")
    return m, y


def attach(request, obj, field, d, remove_key=None):
    f = request.FILES.get(field)
    if f is not None:
        check_upload(f)
        setattr(obj, field, f)
    elif remove_key and to_bool(d.get(remove_key)):
        setattr(obj, field, None)


class CompCrud(CrudBase):
    permission_classes = [IsComplianceUser]
    parser_classes = PARSERS


# ===============================================================
# registrations
# ===============================================================
class RegistrationViewSet(CompCrud):
    """
    GET  /api/compliance/registrations/   ?reg_type=PF|ESIC|PT|TDS|LWF|SHOPS|OTHER ?state= ?branch= ?search=
    POST /api/compliance/registrations/   {reg_type, number, state?, state_code?, branch?, authority?, registered_on?,
                                           valid_until?, due_day?, notes?}
    GET|PATCH|PUT|DELETE .../<id>/        POST .../<id>/update|delete/
    """
    model, code, select, status_field = ComplianceRegistration, "COMPLIANCE_REGISTRATION", ("branch",), "reg_type"
    search_fields = ("number", "state", "authority")

    def filter(self, qs, p):
        qs = super().filter(qs, p)
        if p.get("state"):
            qs = qs.filter(state__iexact=p["state"])
        if p.get("branch"):
            qs = qs.filter(branch_id=p["branch"])
        return qs

    def build(self, r):
        return {"id": r.id, "reg_type": r.reg_type, "reg_type_label": dict(r.TYPES).get(r.reg_type),
                "number": r.number, "state": r.state, "state_code": r.state_code, "authority": r.authority,
                "branch": {"id": r.branch_id, "name": r.branch.name} if r.branch_id else None,
                "registered_on": iso(r.registered_on), "valid_until": iso(r.valid_until), "due_day": r.due_day,
                "notes": r.notes, "created_at": iso(r.created_at), "updated_at": iso(r.updated_at)}

    def apply(self, o, d, creating):
        if creating or "reg_type" in d:
            o.reg_type = pick(d.get("reg_type"), dict(ComplianceRegistration.TYPES), "reg_type")
        if creating or "number" in d:
            if not str(d.get("number") or "").strip():
                raise ValueError("number is required.")
            o.number = str(d["number"]).strip()[:60]
        for f in ("state", "authority", "notes"):
            if f in d:
                setattr(o, f, d[f] or None)
        if "state_code" in d:
            o.state_code = (d["state_code"] or "").strip().upper()[:6] or None
        if "branch" in d:
            o.branch = branch_of(o.company, d["branch"])
        for f in ("registered_on", "valid_until"):
            if f in d:
                setattr(o, f, to_date(d[f]))
        if o.registered_on and o.valid_until and o.valid_until < o.registered_on:
            raise ValueError("valid_until cannot be before registered_on.")
        if "due_day" in d:
            dd = to_int(d["due_day"])
            if dd is None or not 0 <= dd <= 31:
                raise ValueError("due_day must be 0 (month end) to 31.")
            o.due_day = dd
        elif creating:
            o.due_day = DEFAULT_DUE_DAY.get(o.reg_type, 15)
        if ComplianceRegistration.objects.filter(company=o.company, reg_type=o.reg_type, number__iexact=o.number
                                                 ).exclude(pk=o.pk).exists():
            raise ValueError("This registration number already exists for this type.")


# ===============================================================
# filings  ("Record Filing" / "Statutory Filing History & Challans")
# ===============================================================
class FilingViewSet(CompCrud):
    """
    GET  /api/compliance/filings/      ?filing_type= ?status= ?overdue=true ?month= ?year= ?financial_year= ?quarter=
                                       ?registration= ?from=YYYY-MM-DD ?to= ?search= ?page= ?page_size=
    POST /api/compliance/filings/      json or multipart(receipt): filing_type, period_month+period_year (or
                                       financial_year+quarter for TDS_24Q), registration?, due_date?, description?, code?,
                                       amount_payable?, status?, challan_no?, filed_on?, payment_date?, amount_paid?,
                                       penalty_amount?, remarks?
                                       (due_date is derived from the registration's due_day when omitted)
    GET|PATCH|PUT|DELETE .../<id>/     POST .../<id>/update|delete/
    POST .../<id>/record_payment/      {challan_no, payment_date?, amount_paid?, filed_on?, penalty_amount?, receipt?}
    POST .../<id>/mark_filed/          {filed_on?, challan_no?}          POST .../<id>/reopen/
    GET  .../<id>/receipt/             download the challan / receipt
    POST .../generate/                 {month, year, filing_types?[], registration_ids?[]}  or  {financial_year, quarter}
    GET  .../calculate/?month=&year=   statutory totals from Payroll for the month (read only)
    """
    model, code, select = ComplianceFiling, "COMPLIANCE_FILING", ("registration",)
    search_fields = ("code", "description", "challan_no")
    permission_action_map = {"record_payment": "edit", "mark_filed": "edit", "reopen": "edit", "receipt": "view",
                             "generate": "create", "calculate": "view"}

    def filter(self, qs, p):
        qs = super().filter(qs, p)
        today = timezone.localdate()
        for f, col in (("filing_type", "filing_type"), ("financial_year", "financial_year")):
            if p.get(f):
                qs = qs.filter(**{col: p[f]})
        for f, col in (("month", "period_month"), ("year", "period_year"), ("quarter", "quarter"),
                       ("registration", "registration_id")):
            if p.get(f):
                qs = qs.filter(**{col: p[f]})
        if to_bool(p.get("overdue")):
            qs = qs.filter(due_date__lt=today).exclude(status__in=["FILED", "FILED_PAID"])
        try:
            if p.get("from"):
                qs = qs.filter(due_date__gte=to_date(p["from"]))
            if p.get("to"):
                qs = qs.filter(due_date__lte=to_date(p["to"]))
        except ValueError:
            pass
        return qs

    def build(self, f):
        st = filing_state(f)
        period = (month_label(f.period_month, f.period_year) if f.period_month else
                  (f"Q{f.quarter} FY {f.financial_year}" if f.quarter else f.financial_year))
        return {"id": f.id, "code": f.code, "filing_type": f.filing_type,
                "filing_type_label": dict(f.TYPES).get(f.filing_type), "description": f.description,
                "applicable_period": period, "period_month": f.period_month, "period_year": f.period_year,
                "quarter": f.quarter, "financial_year": f.financial_year, "due_date": iso(f.due_date),
                "challan_no": f.challan_no, "status": f.status, "status_label": dict(f.STATUS).get(f.status),
                **st, "can_record_payment": f.status != "FILED_PAID" and f.filing_type not in NO_PAYMENT_TYPES,
                "amount_payable": float(f.amount_payable), "amount_paid": float(f.amount_paid)
                if f.amount_paid is not None else None, "filed_on": iso(f.filed_on),
                "payment_date": iso(f.payment_date), "penalty_amount": float(f.penalty_amount),
                "registration": {"id": f.registration_id, "number": f.registration.number,
                                 "state_code": f.registration.state_code} if f.registration_id else None,
                "receipt": {"file_name": file_name(f.receipt), "url": file_url(self.request, f.receipt),
                            "download_url": f"/api/compliance/filings/{f.id}/receipt/"} if f.receipt else None,
                "remarks": f.remarks, "created_at": iso(f.created_at), "updated_at": iso(f.updated_at)}

    # ---- create / update ----
    def apply(self, o, d, creating):
        if creating or "filing_type" in d:
            o.filing_type = pick(d.get("filing_type"), dict(ComplianceFiling.TYPES), "filing_type")
        if "registration" in d or creating:
            o.registration = reg_of(o.company, d.get("registration"))
        if o.registration_id and REG_FOR.get(o.filing_type) not in (None, o.registration.reg_type):
            raise ValueError(f"A {o.filing_type} filing needs a {REG_FOR[o.filing_type]} registration.")
        if o.filing_type == "TDS_24Q":
            fy = d.get("financial_year", o.financial_year)
            parse_fy(fy)
            q = to_int(d.get("quarter"), o.quarter)
            if q not in (1, 2, 3, 4):
                raise ValueError("quarter (1-4) and financial_year are required for a TDS return.")
            o.financial_year, o.quarter, o.period_month, o.period_year = fy, q, None, None
        else:
            m, y = month_year(d, o)
            if not m or not y:
                raise ValueError("period_month and period_year are required.")
            o.period_month, o.period_year, o.quarter = m, y, None
            o.financial_year = fy_of(timezone.localdate().replace(year=y, month=m, day=1))
        code, desc = filing_defaults(o.filing_type, o.registration, d.get("description"))
        if creating or "code" in d:
            o.code = (d.get("code") or code or "")[:30] or None
        if creating or "description" in d or "filing_type" in d:
            o.description = (d.get("description") or desc or "")[:200]
        if not o.description:
            raise ValueError("description is required for an OTHER filing.")
        if "due_date" in d and d["due_date"]:
            o.due_date = to_date(d["due_date"])
        elif creating or o.due_date is None:
            if o.filing_type == "TDS_24Q":
                o.due_date = tds_due(o.financial_year, o.quarter)
            elif o.period_month:
                dd = o.registration.due_day if o.registration_id else DEFAULT_DUE_DAY.get(REG_FOR.get(o.filing_type, "OTHER"), 15)
                o.due_date = due_for_month(o.period_month, o.period_year, dd)
            else:
                raise ValueError("due_date is required.")
        o.amount_payable = money(d, "amount_payable", o.amount_payable or Decimal("0"))
        if "amount_paid" in d:
            o.amount_paid = money(d, "amount_paid")
        if "penalty_amount" in d:
            o.penalty_amount = money(d, "penalty_amount", Decimal("0"))
        for f in ("challan_no", "remarks"):
            if f in d:
                setattr(o, f, (str(d[f]).strip() if d[f] else None))
        for f in ("filed_on", "payment_date"):
            if f in d:
                setattr(o, f, to_date(d[f]))
        if "status" in d:
            o.status = pick(d["status"], dict(ComplianceFiling.STATUS), "status")
        if o.status == "FILED_PAID":
            o.payment_date = o.payment_date or timezone.localdate()
            o.filed_on = o.filed_on or o.payment_date
            if o.amount_paid is None:
                o.amount_paid = o.amount_payable
        attach(self.request, o, "receipt", d, "remove_receipt")
        self.check_duplicates(o)

    def check_duplicates(self, o):
        key = dict(company=o.company, is_active=True, filing_type=o.filing_type, registration=o.registration,
                   period_year=o.period_year, period_month=o.period_month, quarter=o.quarter,
                   financial_year=o.financial_year if o.filing_type == "TDS_24Q" else o.financial_year)
        if ComplianceFiling.objects.filter(**key).exclude(pk=o.pk).exists():
            raise ValueError("A filing for this type, registration and period already exists.")
        if o.challan_no and ComplianceFiling.objects.filter(company=o.company, is_active=True,
                                                            challan_no__iexact=o.challan_no).exclude(pk=o.pk).exists():
            raise ValueError("This challan / ECR number is already recorded against another filing.")

    # ---- actions ----
    def _get(self, pk):
        return self.scope().filter(pk=pk, is_active=True).first()

    @action(detail=True, methods=["post"])
    def record_payment(self, request, pk=None):
        f = self._get(pk)
        if f is None:
            return err("NOT_FOUND", "Filing not found.", 404)
        if f.filing_type in NO_PAYMENT_TYPES:
            return err("VALIDATION", "A TDS quarterly return has no payment - use mark_filed.")
        if f.status == "FILED_PAID":
            return err("VALIDATION", "Payment is already recorded for this filing.")
        d = request.data
        try:
            if not str(d.get("challan_no") or "").strip():
                raise ValueError("challan_no is required.")
            f.challan_no = str(d["challan_no"]).strip()
            f.payment_date = to_date(d.get("payment_date")) or timezone.localdate()
            f.amount_paid = money(d, "amount_paid", f.amount_payable)
            f.filed_on = to_date(d.get("filed_on")) or f.filed_on or f.payment_date
            if "penalty_amount" in d:
                f.penalty_amount = money(d, "penalty_amount", Decimal("0"))
            f.status = "FILED_PAID"
            attach(request, f, "receipt", d)
            self.check_duplicates(f)
        except ValueError as e:
            return err("VALIDATION", str(e))
        f.updated_by = self.actor()
        f.save()
        return ok("COMPLIANCE_FILING_PAID", "Payment recorded.", self.build(f))

    @action(detail=True, methods=["post"])
    def mark_filed(self, request, pk=None):
        f = self._get(pk)
        if f is None:
            return err("NOT_FOUND", "Filing not found.", 404)
        if f.status == "FILED_PAID":
            return err("VALIDATION", "This filing is already filed and paid.")
        d = request.data
        try:
            f.filed_on = to_date(d.get("filed_on")) or timezone.localdate()
            if d.get("challan_no"):
                f.challan_no = str(d["challan_no"]).strip()
            f.status = "FILED" if (f.filing_type in NO_PAYMENT_TYPES or not f.amount_payable) else "PENDING_PAYMENT"
            self.check_duplicates(f)
        except ValueError as e:
            return err("VALIDATION", str(e))
        f.updated_by = self.actor()
        f.save()
        return ok("COMPLIANCE_FILING_FILED", "Filing marked as filed.", self.build(f))

    @action(detail=True, methods=["post"])
    def reopen(self, request, pk=None):
        f = self._get(pk)
        if f is None:
            return err("NOT_FOUND", "Filing not found.", 404)
        f.status = "PENDING_FILING" if f.filing_type in NO_PAYMENT_TYPES else "PENDING_PAYMENT"
        f.payment_date, f.amount_paid, f.updated_by = None, None, self.actor()
        if f.filing_type in NO_PAYMENT_TYPES:
            f.filed_on = None
        f.save()
        return ok("COMPLIANCE_FILING_REOPENED", "Filing reopened.", self.build(f))

    @action(detail=True, methods=["get"])
    def receipt(self, request, pk=None):
        f = self._get(pk)
        if f is None or not f.receipt:
            raise Http404("Receipt not found.")
        return send_file(f.receipt)

    @action(detail=False, methods=["get"])
    def calculate(self, request):
        p = request.query_params
        try:
            m, y = to_int(p.get("month")), to_int(p.get("year"))
            if not m or not y or not 1 <= m <= 12:
                raise ValueError("month (1-12) and year are required.")
        except ValueError as e:
            return err("VALIDATION", str(e))
        agg = payroll_by_month(self.company(), [(y, m)]).get((y, m))
        return ok("COMPLIANCE_CALCULATION", "Statutory totals from payroll.", {
            "period": month_label(m, y), "payroll_processed": agg is not None,
            "employees": agg["employees"] if agg else 0, "gross_salary": agg["gross"] if agg else 0,
            "pf_deducted": agg["pf"] if agg else 0, "esi_deducted": agg["esi"] if agg else 0,
            "tds_deducted": agg["tds"] if agg else 0,
            "basis": "Sum of Employee.Payroll PF_deduction / ESI_deduction / TDS_deduction for the month "
                     "(employee-side deductions only; add employer share when recording the challan)."})

    @action(detail=False, methods=["post"])
    @transaction.atomic
    def generate(self, request):
        """Create the missing filings for a wage month (PF/ESIC/PT/LWF) or a TDS quarter from the registrations."""
        d, company = request.data, self.company()
        regs = ComplianceRegistration.objects.filter(company=company, is_active=True)
        created, skipped = [], []
        try:
            if d.get("quarter"):
                fy, q = d.get("financial_year"), to_int(d.get("quarter"))
                parse_fy(fy)
                months = quarter_months(fy, q)
                agg = payroll_by_month(company, months)
                tds_amt = sum(a["tds"] for a in agg.values())
                targets = [(r, "TDS_24Q") for r in regs.filter(reg_type="TDS")]
                if not targets:
                    raise ValueError("Add a TDS (TAN) registration first.")
                due = tds_due(fy, q)
                for r, ft in targets:
                    created_or_skip = self._make(company, r, ft, None, None, q, fy, due, Decimal(str(tds_amt)),
                                                 created, skipped)
            else:
                m, y = to_int(d.get("month")), to_int(d.get("year"))
                if not m or not y or not 1 <= m <= 12:
                    raise ValueError("month (1-12) and year are required (or financial_year + quarter for TDS).")
                want = d.get("filing_types") or ["PF_ECR", "ESIC", "PT", "LWF"]
                want = [pick(t, [t for t in REG_FOR if t != "TDS_24Q"], "filing_types") for t in want]
                ids = {to_int(i) for i in (d.get("registration_ids") or [])}
                agg = payroll_by_month(company, [(y, m)]).get((y, m)) or {"pf": 0, "esi": 0}
                amt = {"PF_ECR": agg["pf"], "ESIC": agg["esi"], "PT": 0, "LWF": 0}
                found = False
                for ft in want:
                    for r in regs.filter(reg_type=REG_FOR[ft]):
                        if ids and r.id not in ids:
                            continue
                        found = True
                        self._make(company, r, ft, m, y, None, fy_of(timezone.localdate().replace(year=y, month=m, day=1)),
                                   due_for_month(m, y, r.due_day), Decimal(str(amt[ft])), created, skipped)
                if not found:
                    raise ValueError("No matching registration found. Add the registration first.")
        except ValueError as e:
            transaction.set_rollback(True)
            return err("VALIDATION", str(e))
        return ok("COMPLIANCE_FILINGS_GENERATED", f"{len(created)} filing(s) created, {len(skipped)} skipped.",
                  {"created": [self.build(f) for f in created], "skipped": skipped}, 201 if created else 200)

    def _make(self, company, reg, ft, m, y, q, fy, due, amount, created, skipped):
        exists = ComplianceFiling.objects.filter(company=company, is_active=True, filing_type=ft, registration=reg,
                                                 period_month=m, period_year=y, quarter=q, financial_year=fy).exists()
        if exists:
            skipped.append({"registration": reg.number, "filing_type": ft, "reason": "already exists"})
            return
        code, desc = filing_defaults(ft, reg)
        f = ComplianceFiling.objects.create(
            company=company, registration=reg, filing_type=ft, code=code, description=desc, period_month=m,
            period_year=y, quarter=q, financial_year=fy, due_date=due, amount_payable=amount,
            status="PENDING_FILING" if ft in NO_PAYMENT_TYPES else "PENDING_PAYMENT", created_by=self.actor(),
            updated_by=self.actor())
        created.append(f)


# ===============================================================
# documents vault
# ===============================================================
class DocumentViewSet(CompCrud):
    """
    GET  /api/compliance/documents/   ?doc_type= ?year= ?month= ?financial_year= ?filing= ?branch= ?search=
    POST /api/compliance/documents/   multipart: title, doc_type?, file, period_month?, period_year?, financial_year?,
                                      filing?, registration?, branch?, notes?
    GET|PATCH|PUT|DELETE .../<id>/    POST .../<id>/update|delete/        GET .../<id>/download/
    """
    model, code, select, status_field = ComplianceDocument, "COMPLIANCE_DOCUMENT", ("branch", "filing"), "doc_type"
    search_fields = ("title", "notes")
    permission_action_map = {"download": "view"}

    def filter(self, qs, p):
        qs = super().filter(qs, p)
        for f, col in (("year", "period_year"), ("month", "period_month"), ("financial_year", "financial_year"),
                       ("filing", "filing_id"), ("branch", "branch_id"), ("registration", "registration_id")):
            if p.get(f):
                qs = qs.filter(**{col: p[f]})
        return qs

    def build(self, o):
        return {"id": o.id, "title": o.title, "doc_type": o.doc_type, "doc_type_label": dict(o.TYPES).get(o.doc_type),
                "period_month": o.period_month, "period_year": o.period_year, "financial_year": o.financial_year,
                "period_label": month_label(o.period_month, o.period_year),
                "filing_id": o.filing_id, "registration_id": o.registration_id,
                "branch": {"id": o.branch_id, "name": o.branch.name} if o.branch_id else None, "notes": o.notes,
                "file_name": file_name(o.file), "file_url": file_url(self.request, o.file),
                "download_url": f"/api/compliance/documents/{o.id}/download/" if o.file else None,
                "uploaded_by": o.uploaded_by, "uploaded_by_name": actor_name(o.company, o.uploaded_by),
                "created_at": iso(o.created_at), "updated_at": iso(o.updated_at)}

    def apply(self, o, d, creating):
        if creating or "title" in d:
            if not str(d.get("title") or "").strip():
                raise ValueError("title is required.")
            o.title = str(d["title"]).strip()[:200]
        if "doc_type" in d:
            o.doc_type = pick(d["doc_type"], dict(ComplianceDocument.TYPES), "doc_type")
        if "period_month" in d or "period_year" in d:
            o.period_month, o.period_year = month_year(d, o)
        if "financial_year" in d:
            if d["financial_year"]:
                parse_fy(d["financial_year"])
            o.financial_year = d["financial_year"] or None
        if "filing" in d:
            o.filing = (ComplianceFiling.objects.filter(company=o.company, pk=to_int(d["filing"]), is_active=True).first()
                        if d["filing"] not in (None, "") else None)
            if d["filing"] not in (None, "") and o.filing is None:
                raise ValueError("filing is invalid.")
        if "registration" in d:
            o.registration = reg_of(o.company, d["registration"])
        if "branch" in d:
            o.branch = branch_of(o.company, d["branch"])
        if "notes" in d:
            o.notes = d["notes"]
        if creating:
            o.uploaded_by = self.actor()
        attach(self.request, o, "file", d, "remove_file")
        if creating and not o.file:
            raise ValueError("file is required (multipart/form-data).")
        if ComplianceDocument.objects.filter(company=o.company, is_active=True, title__iexact=o.title,
                                             doc_type=o.doc_type, period_month=o.period_month,
                                             period_year=o.period_year, branch=o.branch).exclude(pk=o.pk).exists():
            raise ValueError("A document with the same title, type, period and branch already exists.")

    @action(detail=True, methods=["get"])
    def download(self, request, pk=None):
        o = self.scope().filter(pk=pk, is_active=True).first()
        if o is None or not o.file:
            raise Http404("File not found.")
        return send_file(o.file)


# ===============================================================
# labour licences / inspections / reminders / form 16
# ===============================================================
class LicenseViewSet(CompCrud):
    """
    GET  /api/compliance/licenses/   ?license_type= ?branch= ?state=ACTIVE|EXPIRING|EXPIRED ?search=
    POST /api/compliance/licenses/   multipart/json(file): license_type, license_number, branch?, authority?, issued_on?,
                                     valid_until?, reminder_days?, notes?
    GET|PATCH|PUT|DELETE .../<id>/   POST .../<id>/update|delete/   POST .../<id>/renew/ {valid_until, issued_on?, license_number?}
    GET .../<id>/download/
    """
    model, code, select, status_field = LabourLicense, "LABOUR_LICENSE", ("branch",), "license_type"
    search_fields = ("license_number", "authority")
    permission_action_map = {"renew": "edit", "download": "view"}

    def build(self, l):
        st, left = license_state(l)
        return {"id": l.id, "license_type": l.license_type, "license_type_label": dict(l.TYPES).get(l.license_type),
                "license_number": l.license_number, "authority": l.authority,
                "branch": {"id": l.branch_id, "name": l.branch.name} if l.branch_id else None,
                "issued_on": iso(l.issued_on), "valid_until": iso(l.valid_until), "reminder_days": l.reminder_days,
                "state": st, "days_left": left, "notes": l.notes,
                "file_name": file_name(l.file), "download_url": f"/api/compliance/licenses/{l.id}/download/"
                if l.file else None, "created_at": iso(l.created_at), "updated_at": iso(l.updated_at)}

    def list(self, request):
        p = request.query_params
        qs = self.filter(self.scope().filter(is_active=True), p)
        if p.get("branch"):
            qs = qs.filter(branch_id=p["branch"])
        items = list(qs)
        if p.get("state"):
            items = [l for l in items if license_state(l)[0] == p["state"].upper()]
        rows, meta = paginate(request, items, self.build)
        return ok("LABOUR_LICENSE_LIST", "List fetched.", rows, meta=meta)

    def apply(self, o, d, creating):
        if creating or "license_type" in d:
            o.license_type = pick(d.get("license_type"), dict(LabourLicense.TYPES), "license_type")
        if creating or "license_number" in d:
            if not str(d.get("license_number") or "").strip():
                raise ValueError("license_number is required.")
            o.license_number = str(d["license_number"]).strip()[:80]
        if "authority" in d:
            o.authority = d["authority"] or None
        if "notes" in d:
            o.notes = d["notes"]
        if "branch" in d:
            o.branch = branch_of(o.company, d["branch"])
        for f in ("issued_on", "valid_until"):
            if f in d:
                setattr(o, f, to_date(d[f]))
        if o.issued_on and o.valid_until and o.valid_until < o.issued_on:
            raise ValueError("valid_until cannot be before issued_on.")
        if "reminder_days" in d:
            rd = to_int(d["reminder_days"])
            if rd is None or not 0 <= rd <= 365:
                raise ValueError("reminder_days must be 0-365.")
            o.reminder_days = rd
        attach(self.request, o, "file", d, "remove_file")
        if LabourLicense.objects.filter(company=o.company, license_type=o.license_type,
                                        license_number__iexact=o.license_number).exclude(pk=o.pk).exists():
            raise ValueError("This licence number already exists for this licence type.")

    @action(detail=True, methods=["post"])
    def renew(self, request, pk=None):
        l = self.scope().filter(pk=pk, is_active=True).first()
        if l is None:
            return err("NOT_FOUND", "Licence not found.", 404)
        try:
            vu = to_date(request.data.get("valid_until"))
            if vu is None:
                raise ValueError("valid_until is required.")
            if l.valid_until and vu <= l.valid_until:
                raise ValueError("The new valid_until must be later than the current one.")
            l.valid_until = vu
            if request.data.get("issued_on"):
                l.issued_on = to_date(request.data["issued_on"])
            if request.data.get("license_number"):
                l.license_number = str(request.data["license_number"]).strip()
            attach(request, l, "file", request.data)
        except ValueError as e:
            return err("VALIDATION", str(e))
        l.updated_by = self.actor()
        l.save()
        return ok("LABOUR_LICENSE_RENEWED", "Licence renewed.", self.build(l))

    @action(detail=True, methods=["get"])
    def download(self, request, pk=None):
        l = self.scope().filter(pk=pk, is_active=True).first()
        if l is None or not l.file:
            raise Http404("File not found.")
        return send_file(l.file)


class InspectionViewSet(CompCrud):
    """
    GET  /api/compliance/inspections/  ?status=OPEN|CLOSED ?outcome= ?branch= ?from= ?to= ?search=
    POST /api/compliance/inspections/  multipart/json(report): inspection_date, branch?, authority?, inspector_name?, scope?,
                                       outcome?, observations?, action_due_date?, penalty_amount?
    GET|PATCH|PUT|DELETE .../<id>/     POST .../<id>/update|delete/     POST .../<id>/close/     GET .../<id>/download/
    """
    model, code, select = LabourInspection, "LABOUR_INSPECTION", ("branch",)
    search_fields = ("authority", "inspector_name", "scope", "observations")
    permission_action_map = {"close": "edit", "download": "view"}

    def filter(self, qs, p):
        qs = super().filter(qs, p)
        if p.get("outcome"):
            qs = qs.filter(outcome=p["outcome"].upper())
        if p.get("branch"):
            qs = qs.filter(branch_id=p["branch"])
        try:
            if p.get("from"):
                qs = qs.filter(inspection_date__gte=to_date(p["from"]))
            if p.get("to"):
                qs = qs.filter(inspection_date__lte=to_date(p["to"]))
        except ValueError:
            pass
        return qs

    def build(self, i):
        return {"id": i.id, "inspection_date": iso(i.inspection_date), "authority": i.authority,
                "inspector_name": i.inspector_name, "scope": i.scope, "outcome": i.outcome,
                "outcome_label": dict(i.OUTCOME).get(i.outcome), "observations": i.observations,
                "action_due_date": iso(i.action_due_date), "penalty_amount": float(i.penalty_amount),
                "status": i.status, "branch": {"id": i.branch_id, "name": i.branch.name} if i.branch_id else None,
                "report_name": file_name(i.report),
                "download_url": f"/api/compliance/inspections/{i.id}/download/" if i.report else None,
                "created_at": iso(i.created_at), "updated_at": iso(i.updated_at)}

    def apply(self, o, d, creating):
        if creating or "inspection_date" in d:
            o.inspection_date = to_date(d.get("inspection_date"))
            if o.inspection_date is None:
                raise ValueError("inspection_date is required.")
        for f in ("authority", "inspector_name", "scope", "observations"):
            if f in d:
                setattr(o, f, d[f] or None)
        if "outcome" in d:
            o.outcome = pick(d["outcome"], dict(LabourInspection.OUTCOME), "outcome")
        if "status" in d:
            o.status = pick(d["status"], dict(LabourInspection.STATUS), "status")
        if "branch" in d:
            o.branch = branch_of(o.company, d["branch"])
        if "action_due_date" in d:
            o.action_due_date = to_date(d["action_due_date"])
        if o.action_due_date and o.action_due_date < o.inspection_date:
            raise ValueError("action_due_date cannot be before the inspection date.")
        if "penalty_amount" in d:
            o.penalty_amount = money(d, "penalty_amount", Decimal("0"))
        attach(self.request, o, "report", d, "remove_report")
        if LabourInspection.objects.filter(company=o.company, is_active=True, inspection_date=o.inspection_date,
                                           branch=o.branch, authority=o.authority).exclude(pk=o.pk).exists():
            raise ValueError("An inspection by this authority on this date for this branch already exists.")

    @action(detail=True, methods=["post"])
    def close(self, request, pk=None):
        i = self.scope().filter(pk=pk, is_active=True).first()
        if i is None:
            return err("NOT_FOUND", "Inspection not found.", 404)
        i.status, i.updated_by = "CLOSED", self.actor()
        i.save()
        return ok("LABOUR_INSPECTION_CLOSED", "Inspection closed.", self.build(i))

    @action(detail=True, methods=["get"])
    def download(self, request, pk=None):
        i = self.scope().filter(pk=pk, is_active=True).first()
        if i is None or not i.report:
            raise Http404("File not found.")
        return send_file(i.report)


class ReminderViewSet(CompCrud):
    """
    GET  /api/compliance/reminders/   ?done=true|false ?severity= ?search=
    POST /api/compliance/reminders/   {title, message?, due_date?, severity?, filing?}
    GET|PATCH|PUT|DELETE .../<id>/    POST .../<id>/update|delete/     POST .../<id>/complete/   POST .../<id>/reopen/
    """
    model, code, status_field = ComplianceReminder, "COMPLIANCE_REMINDER", "severity"
    search_fields = ("title", "message")
    permission_action_map = {"complete": "edit", "reopen": "edit"}

    def filter(self, qs, p):
        qs = super().filter(qs, p)
        return qs.filter(is_done=to_bool(p["done"])) if p.get("done") else qs

    def build(self, r):
        return {"id": r.id, "title": r.title, "message": r.message, "due_date": iso(r.due_date),
                "severity": r.severity, "filing_id": r.filing_id, "is_done": r.is_done, "done_at": iso(r.done_at),
                "created_at": iso(r.created_at), "updated_at": iso(r.updated_at)}

    def apply(self, o, d, creating):
        if creating or "title" in d:
            if not str(d.get("title") or "").strip():
                raise ValueError("title is required.")
            o.title = str(d["title"]).strip()[:200]
        if "message" in d:
            o.message = d["message"]
        if "due_date" in d:
            o.due_date = to_date(d["due_date"])
        if "severity" in d:
            o.severity = pick(d["severity"], dict(ComplianceReminder.SEVERITY), "severity")
        if "filing" in d:
            o.filing = (ComplianceFiling.objects.filter(company=o.company, pk=to_int(d["filing"]),
                                                        is_active=True).first() if d["filing"] not in (None, "") else None)
            if d["filing"] not in (None, "") and o.filing is None:
                raise ValueError("filing is invalid.")
        if ComplianceReminder.objects.filter(company=o.company, is_active=True, is_done=False,
                                             title__iexact=o.title, due_date=o.due_date).exclude(pk=o.pk).exists():
            raise ValueError("An open reminder with this title and due date already exists.")

    def _set(self, pk, done):
        r = self.scope().filter(pk=pk, is_active=True).first()
        if r is None:
            return err("NOT_FOUND", "Reminder not found.", 404)
        r.is_done, r.done_at, r.updated_by = done, timezone.now() if done else None, self.actor()
        r.save()
        return ok("COMPLIANCE_REMINDER_UPDATED", "Updated.", self.build(r))

    @action(detail=True, methods=["post"])
    def complete(self, request, pk=None):
        return self._set(pk, True)

    @action(detail=True, methods=["post"])
    def reopen(self, request, pk=None):
        return self._set(pk, False)


class Form16ViewSet(CompCrud):
    """
    GET  /api/compliance/form16/   ?financial_year= ?employee=<code> ?published=true|false ?search=
    POST /api/compliance/form16/   multipart: employee_code, financial_year, file, part?, gross_income?, tds_deducted?,
                                   issued_on?, is_published?
    GET|PATCH|PUT|DELETE .../<id>/ POST .../<id>/update|delete/   GET .../<id>/download/
    """
    model, code, select, status_field = Form16Record, "FORM16", ("employee",), "financial_year"
    permission_action_map = {"download": "view"}

    def filter(self, qs, p):
        qs = super().filter(qs, p)
        if p.get("published"):
            qs = qs.filter(is_published=to_bool(p["published"]))
        q = (p.get("search") or "").strip()
        return qs.filter(Q(employee__name__icontains=q) | Q(employee__employee_code__icontains=q)) if q else qs

    def build(self, r):
        return {"id": r.id, "employee": emp_brief(r.employee, self.request), "financial_year": r.financial_year,
                "part": r.part, "part_label": dict(r.PARTS).get(r.part),
                "gross_income": float(r.gross_income) if r.gross_income is not None else None,
                "tds_deducted": float(r.tds_deducted) if r.tds_deducted is not None else None,
                "issued_on": iso(r.issued_on), "is_published": r.is_published, "file_name": file_name(r.file),
                "download_url": f"/api/compliance/form16/{r.id}/download/" if r.file else None,
                "created_at": iso(r.created_at), "updated_at": iso(r.updated_at)}

    def apply(self, o, d, creating):
        if creating:
            o.employee = emp_by_code(o.company, d.get("employee_code"))
        if creating or "financial_year" in d:
            parse_fy(d.get("financial_year"))
            o.financial_year = str(d["financial_year"]).strip()
        if "part" in d:
            o.part = pick(d["part"], dict(Form16Record.PARTS), "part")
        for f in ("gross_income", "tds_deducted"):
            if f in d:
                setattr(o, f, money(d, f))
        if "issued_on" in d:
            o.issued_on = to_date(d["issued_on"])
        elif creating:
            o.issued_on = timezone.localdate()
        if "is_published" in d:
            o.is_published = to_bool(d["is_published"], True)
        attach(self.request, o, "file", d, "remove_file")
        if creating and not o.file:
            raise ValueError("file is required (multipart/form-data).")
        if Form16Record.objects.filter(company=o.company, employee=o.employee, financial_year=o.financial_year,
                                       part=o.part).exclude(pk=o.pk).exists():
            raise ValueError("A Form 16 of this part is already recorded for this employee and financial year.")

    @action(detail=True, methods=["get"])
    def download(self, request, pk=None):
        r = self.scope().filter(pk=pk, is_active=True).first()
        if r is None or not r.file:
            raise Http404("File not found.")
        return send_file(r.file)


# ===============================================================
# dashboard + tabs + alerts + meta   (read only, computed from the data above)
# ===============================================================
def _filing_brief(f):
    st = filing_state(f)
    return {"id": f.id, "code": f.code, "description": f.description, "due_date": iso(f.due_date),
            "status": f.status, "status_label": dict(f.STATUS).get(f.status), "challan_no": f.challan_no,
            "applicable_period": month_label(f.period_month, f.period_year) or (
                f"Q{f.quarter} FY {f.financial_year}" if f.quarter else None), **st}


class ComplianceBase(ComplianceAuthMixin, ViewSet):
    pass


class DashboardViewSet(ComplianceBase):
    """GET /api/compliance/dashboard/   ?filing_type= ?status= ?year= ?month= ?page= ?page_size="""

    def list(self, request):
        company, today = self.company(), timezone.localdate()
        base = ComplianceFiling.objects.filter(company=company, is_active=True).select_related("registration")
        due_so_far = list(base.filter(due_date__lte=today))
        on_time = sum(1 for f in due_so_far if is_complete(f) and not filing_state(f, today)["paid_late"])
        score = round(on_time * 100 / len(due_so_far)) if due_so_far else None
        penalties = float((base.aggregate(s=Sum("penalty_amount"))["s"] or 0)
                          + (LabourInspection.objects.filter(company=company, is_active=True).aggregate(
                              s=Sum("penalty_amount"))["s"] or 0))
        members, total = pf_members(company).count(), active_employees(company).count()
        pending = base.exclude(status__in=["FILED", "FILED_PAID"])
        upcoming = pending.filter(due_date__gte=today).order_by("due_date")
        nxt = upcoming.first()
        next_block = None
        if nxt:
            same = list(upcoming.filter(due_date=nxt.due_date))
            next_block = {"date": iso(nxt.due_date), "label": f"{nxt.due_date.day} {nxt.due_date:%b}",
                          "days_left": (nxt.due_date - today).days, "subtitle": " & ".join(
                              dict.fromkeys(f.code or f.description for f in same)),
                          "filings": [_filing_brief(f) for f in same]}
        tds = base.filter(filing_type="TDS_24Q").order_by("-financial_year", "-quarter").first()
        f16 = None
        if tds:
            f16 = Form16Record.objects.filter(company=company, is_active=True, financial_year=tds.financial_year
                                              ).values("employee").distinct().count()
        p = request.query_params
        hist = base
        for f, col in (("filing_type", "filing_type"), ("status", "status"), ("year", "period_year"),
                       ("month", "period_month")):
            if p.get(f):
                hist = hist.filter(**{col: p[f]})
        rows, meta = paginate(request, hist.order_by("-due_date", "-id"),
                              lambda f: _filing_brief(f) | {"can_record_payment": f.status != "FILED_PAID" and
                                                            f.filing_type not in NO_PAYMENT_TYPES})
        return ok("COMPLIANCE_DASHBOARD", "Statutory Compliance & Legal Governance.", {
            "title": "Statutory Compliance & Legal Governance",
            "subtitle": "PF, ESI, Professional Tax, TDS filings, and government labor registers",
            "kpis": {
                "compliance_score": {"value": score, "unit": "%", "label": "Statutory compliance score",
                                     "subtitle": "Zero penalties incurred" if not penalties else
                                     f"Rs. {penalties:,.2f} penalties incurred",
                                     "filings_due": len(due_so_far), "filed_on_time": on_time,
                                     "overdue": sum(1 for f in due_so_far if not is_complete(f)),
                                     "penalties": penalties},
                "pf_active_members": {"value": members, "label": "PF active members", "total_employees": total,
                                      "subtitle": "All full-time staff" if members == total and total else
                                      f"{members} of {total} active employees"},
                "next_filing_due": next_block or {"date": None, "label": None, "subtitle": "No upcoming filings"},
                "tds_status": {"value": f"Q{tds.quarter} {'Filed' if is_complete(tds) else 'Pending'}" if tds else None,
                               "label": "TDS 24Q status", "financial_year": tds.financial_year if tds else None,
                               "form16_issued": f16,
                               "subtitle": (f"Form 16 issued: {f16}" if f16 is not None else None)}},
            "filings": rows}, meta=meta)


class StatutoryTabViewSet(ComplianceBase):
    """GET /api/compliance/pf/  esi/  pt/  tds/  (one registered viewset per tab, see compliance_urls.py)"""
    kind = None

    def _months(self, request):
        fy = request.query_params.get("financial_year")
        return fy, (fy_months(fy) if fy else sorted(last_months(12)))


class PfViewSet(StatutoryTabViewSet):
    def list(self, request):
        c = self.company()
        fy, pairs = self._months(request)
        agg = payroll_by_month(c, pairs)
        filings = {(f.period_year, f.period_month): f for f in ComplianceFiling.objects.filter(
            company=c, is_active=True, filing_type="PF_ECR")}
        mem = pf_members(c)
        uan = uan_count(mem)
        monthly = [{"year": y, "month": m, "label": month_label(m, y), "employees_with_payroll":
                    agg.get((y, m), {}).get("employees", 0), "employee_pf_deducted": agg.get((y, m), {}).get("pf", 0),
                    "filing": _filing_brief(filings[(y, m)]) if (y, m) in filings else None} for y, m in pairs]
        regs = ComplianceRegistration.objects.filter(company=c, is_active=True, reg_type="PF")
        return ok("COMPLIANCE_PF", "EPF overview.", {
            "registrations": [{"id": r.id, "number": r.number, "state": r.state, "valid_until": iso(r.valid_until)}
                              for r in regs],
            "members": {"covered": mem.count(), "total_employees": active_employees(c).count(),
                        "with_uan": uan, "without_uan": mem.count() - uan},
            "monthly": monthly, "pending_filings": [_filing_brief(f) for f in ComplianceFiling.objects.filter(
                company=c, is_active=True, filing_type="PF_ECR").exclude(status__in=["FILED", "FILED_PAID"])
                .order_by("due_date")]})


class EsiViewSet(StatutoryTabViewSet):
    def list(self, request):
        c = self.company()
        fy, pairs = self._months(request)
        agg = payroll_by_month(c, pairs)
        filings = {(f.period_year, f.period_month): f for f in ComplianceFiling.objects.filter(
            company=c, is_active=True, filing_type="ESIC")}
        mem = esi_members(c)
        regs = ComplianceRegistration.objects.filter(company=c, is_active=True, reg_type="ESIC")
        return ok("COMPLIANCE_ESI", "ESIC overview.", {
            "registrations": [{"id": r.id, "number": r.number, "state": r.state, "valid_until": iso(r.valid_until)}
                              for r in regs],
            "members": {"covered": mem.count(), "total_employees": active_employees(c).count()},
            "monthly": [{"year": y, "month": m, "label": month_label(m, y),
                         "employees_with_payroll": agg.get((y, m), {}).get("employees", 0),
                         "employee_esi_deducted": agg.get((y, m), {}).get("esi", 0),
                         "filing": _filing_brief(filings[(y, m)]) if (y, m) in filings else None} for y, m in pairs],
            "pending_filings": [_filing_brief(f) for f in ComplianceFiling.objects.filter(
                company=c, is_active=True, filing_type="ESIC").exclude(status__in=["FILED", "FILED_PAID"])
                .order_by("due_date")]})


class PtViewSet(StatutoryTabViewSet):
    def list(self, request):
        c = self.company()
        fy, pairs = self._months(request)
        regs = ComplianceRegistration.objects.filter(company=c, is_active=True, reg_type="PT").select_related("branch")
        fl = ComplianceFiling.objects.filter(company=c, is_active=True, filing_type="PT")
        out = []
        for r in regs:
            by = {(f.period_year, f.period_month): f for f in fl.filter(registration=r)}
            out.append({"registration": {"id": r.id, "number": r.number, "state": r.state, "state_code": r.state_code,
                                         "branch": r.branch.name if r.branch_id else None,
                                         "valid_until": iso(r.valid_until)},
                        "monthly": [{"year": y, "month": m, "label": month_label(m, y),
                                     "filing": _filing_brief(by[(y, m)]) if (y, m) in by else None,
                                     "amount_payable": float(by[(y, m)].amount_payable) if (y, m) in by else None}
                                    for y, m in pairs]})
        return ok("COMPLIANCE_PT", "Professional Tax overview.", {
            "registrations": out, "total_paid": float(fl.filter(status="FILED_PAID").aggregate(
                s=Sum("amount_paid"))["s"] or 0), "pending_filings": [_filing_brief(f) for f in fl.exclude(
                status__in=["FILED", "FILED_PAID"]).order_by("due_date")]})


class TdsViewSet(StatutoryTabViewSet):
    """GET /api/compliance/tds/?financial_year=2026-27  (defaults to the current financial year)"""

    def list(self, request):
        c = self.company()
        try:
            fy = request.query_params.get("financial_year") or fy_of(timezone.localdate())
            pairs = fy_months(fy)
        except ValueError as e:
            return err("VALIDATION", str(e))
        agg = payroll_by_month(c, pairs)
        regs = ComplianceRegistration.objects.filter(company=c, is_active=True, reg_type="TDS")
        fl = {f.quarter: f for f in ComplianceFiling.objects.filter(company=c, is_active=True, filing_type="TDS_24Q",
                                                                    financial_year=fy)}
        quarters = []
        for q in (1, 2, 3, 4):
            ms = quarter_months(fy, q)
            quarters.append({"quarter": q, "label": f"Q{q}", "months": [month_label(m, y) for y, m in ms],
                             "tds_deducted": sum(agg.get(p, {}).get("tds", 0) for p in ms),
                             "expected_due_date": iso(tds_due(fy, q)),
                             "filing": _filing_brief(fl[q]) if q in fl else None})
        eligible = set(Payroll.objects.filter(company=c, is_active=True, TDS_deduction__gt=0).filter(
            Q(*[Q(year=y, month=m) for y, m in pairs], _connector=Q.OR)).values_list("Employee_ID", flat=True))
        issued = Form16Record.objects.filter(company=c, is_active=True, financial_year=fy)
        issued_codes = set(issued.values_list("employee__employee_code", flat=True))
        return ok("COMPLIANCE_TDS", "TDS overview.", {
            "financial_year": fy, "registrations": [{"id": r.id, "number": r.number, "valid_until": iso(r.valid_until)}
                                                    for r in regs],
            "quarters": quarters, "monthly_tds": [{"year": y, "month": m, "label": month_label(m, y),
                                                   "tds_deducted": agg.get((y, m), {}).get("tds", 0)} for y, m in pairs],
            "form16": {"eligible_employees": len(eligible), "issued": issued.values("employee").distinct().count(),
                       "pending": len(eligible - issued_codes)}})


class LabourViewSet(ComplianceBase):
    """GET /api/compliance/labour/   status banner + licences + inspections"""

    def list(self, request):
        c, today = self.company(), timezone.localdate()
        lic = list(LabourLicense.objects.filter(company=c, is_active=True).select_related("branch"))
        states = [(l, license_state(l, today)) for l in lic]
        counts = {"ACTIVE": 0, "EXPIRING": 0, "EXPIRED": 0}
        for _, (st, _) in states:
            counts[st] += 1
        if not lic:
            msg, ok_all = "No labour licences recorded yet.", False
        elif counts["EXPIRED"] == 0 and counts["EXPIRING"] == 0:
            types = list(dict.fromkeys(dict(LabourLicense.TYPES)[l.license_type] for l in lic))
            places = sorted(dict.fromkeys(l.branch.name for l in lic if l.branch_id))
            msg = (f"All {' & '.join(types)} licenses" + (f" for {', '.join(places[:-1])}{' and ' if len(places) > 1 else ''}{places[-1]}"
                                                          if places else "") + " are current and active.")
            ok_all = True
        else:
            bad = [f"{dict(LabourLicense.TYPES)[l.license_type]} {l.license_number}" +
                   (f" ({l.branch.name})" if l.branch_id else "") + f" - {st.lower()}"
                   for l, (st, _) in states if st != "ACTIVE"]
            msg, ok_all = f"{len(bad)} licence(s) need attention: " + "; ".join(bad) + ".", False
        insp = LabourInspection.objects.filter(company=c, is_active=True).select_related("branch")
        lv = LicenseViewSet()
        lv.request = request
        iv = InspectionViewSet()
        iv.request = request
        return ok("COMPLIANCE_LABOUR", "Labour Act Licenses & Inspections.", {
            "title": "Labour Act Licenses & Inspections", "banner": {"all_current": ok_all, "message": msg},
            "summary": {"licenses": len(lic), **{k.lower(): v for k, v in counts.items()},
                        "open_inspections": insp.filter(status="OPEN").count(),
                        "penalties": float(insp.aggregate(s=Sum("penalty_amount"))["s"] or 0)},
            "licenses": [lv.build(l) for l in lic], "inspections": [iv.build(i) for i in insp[:50]]})


class AlertsViewSet(ComplianceBase):
    """GET /api/compliance/alerts/  ?days=30 (look-ahead window) ?severity=CRITICAL|WARNING|INFO"""

    def list(self, request):
        try:
            days = max(0, min(int(request.query_params.get("days", 30)), 365))
        except ValueError:
            days = 30
        al = build_alerts(self.company(), days)
        if request.query_params.get("severity"):
            al = [a for a in al if a["severity"] == request.query_params["severity"].upper()]
        return ok("COMPLIANCE_ALERTS", "Statutory Filing Radar & Reminders.", al,
                  summary={"total": len(al), **{s: sum(1 for a in al if a["severity"] == s)
                                                for s in ("CRITICAL", "WARNING", "INFO")}})


class MetaViewSet(ComplianceBase):
    def list(self, request):
        c = self.company()
        return ok("COMPLIANCE_META", "Dropdown values.", {
            "registration_types": [{"code": k, "label": v} for k, v in ComplianceRegistration.TYPES],
            "filing_types": [{"code": k, "label": v, "registration_type": REG_FOR.get(k)}
                             for k, v in ComplianceFiling.TYPES],
            "filing_statuses": [{"code": k, "label": v} for k, v in ComplianceFiling.STATUS],
            "document_types": [{"code": k, "label": v} for k, v in ComplianceDocument.TYPES],
            "license_types": [{"code": k, "label": v} for k, v in LabourLicense.TYPES],
            "inspection_outcomes": [{"code": k, "label": v} for k, v in LabourInspection.OUTCOME],
            "severities": [{"code": k, "label": v} for k, v in ComplianceReminder.SEVERITY],
            "form16_parts": [{"code": k, "label": v} for k, v in Form16Record.PARTS],
            "branches": list(Branch.objects.filter(company=c, is_active=True).values("id", "name")),
            "registrations": [{"id": r.id, "reg_type": r.reg_type, "number": r.number, "state": r.state}
                              for r in ComplianceRegistration.objects.filter(company=c, is_active=True)],
            "current_financial_year": fy_of(timezone.localdate()), "months": MONTHS[1:]})
