# ============================================================
# ADDITIVE: shared helpers for Statutory Compliance (admin + employee side)
# Everything is computed from the database - nothing is hard-coded sample data.
# ============================================================
import calendar
import re
from datetime import date

from django.db.models import Count, Q, Sum
from django.utils import timezone
from rest_framework.permissions import BasePermission

from Employee.employee_crud_permissions import (_role_is_usable, resolve_actor_role, role_allows)
from Employee.models import Payroll

from .common import PeopleAuthMixin, employees_qs, iso
from .compliance_models import (ComplianceFiling, ComplianceReminder, ComplianceRegistration, LabourInspection,
                                LabourLicense)

MONTHS = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
          "November", "December"]
FY_RE = re.compile(r"^(\d{4})-(\d{2})$")
# registration type that backs each filing type
REG_FOR = {"PF_ECR": "PF", "ESIC": "ESIC", "PT": "PT", "TDS_24Q": "TDS", "LWF": "LWF"}
DEFAULT_DUE_DAY = {"PF": 15, "ESIC": 15, "PT": 0, "TDS": 31, "LWF": 15, "SHOPS": 15, "OTHER": 15}   # editable per registration
NO_PAYMENT_TYPES = {"TDS_24Q"}          # filed only - the tax itself is paid through the monthly challan


# ---------------- permissions ----------------
def compliance_allows(user, act):
    """Company admin always; employee via EmployeeRole compliance, payroll OR employees checkboxes."""
    actor = resolve_actor_role(user)
    if actor == "admin":
        return True
    if actor is None:
        return False
    role = _role_is_usable(user)
    if role is None:
        return False
    a = "edit" if act == "approve" else act
    return bool(role_allows(role, "compliance", a) or role_allows(role, "payroll", a) or role_allows(role, "employees", a))


class IsComplianceUser(BasePermission):
    message = "You do not have permission to use the Compliance module (needs Payroll or Employees role access)."
    METHOD_ACTION = {"GET": "view", "HEAD": "view", "OPTIONS": "view", "POST": "create", "PUT": "edit",
                     "PATCH": "edit", "DELETE": "delete"}

    def has_permission(self, request, view):
        act = getattr(view, "permission_action", None)
        if act is None:
            va = getattr(view, "action", None)
            act = {"update_post": "edit", "delete_post": "delete"}.get(va) or (
                getattr(view, "permission_action_map", None) or {}).get(va)
        if act is None:
            act = self.METHOD_ACTION.get(request.method)
        return bool(act) and compliance_allows(request.user, act)


class ComplianceAuthMixin(PeopleAuthMixin):
    permission_classes = [IsComplianceUser]


# ---------------- dates / financial year ----------------
def month_label(m, y):
    return f"{MONTHS[m]} {y}" if m and y else None


def fy_of(d):
    s = d.year if d.month >= 4 else d.year - 1
    return f"{s}-{str(s + 1)[2:]}"


def parse_fy(fy):
    m = FY_RE.match(str(fy or "").strip())
    if not m or (int(m.group(1)) + 1) % 100 != int(m.group(2)):
        raise ValueError("financial_year must look like 2026-27.")
    return int(m.group(1))


def fy_months(fy):
    s = parse_fy(fy)
    return [(s, m) for m in range(4, 13)] + [(s + 1, m) for m in range(1, 4)]


def quarter_months(fy, q):
    if q not in (1, 2, 3, 4):
        raise ValueError("quarter must be 1-4.")
    return fy_months(fy)[(q - 1) * 3:(q - 1) * 3 + 3]


def clamp_day(y, m, day):
    last = calendar.monthrange(y, m)[1]
    return date(y, m, last if day in (0, None) else min(day, last))


def due_for_month(month, year, due_day):
    """Wage month -> due in the following month on due_day (0 = month end)."""
    ny, nm = (year + 1, 1) if month == 12 else (year, month + 1)
    return clamp_day(ny, nm, due_day)


def tds_due(fy, q):
    s = parse_fy(fy)
    return {1: date(s, 7, 31), 2: date(s, 10, 31), 3: date(s + 1, 1, 31), 4: date(s + 1, 5, 31)}[q]


# ---------------- filing state ----------------
def is_complete(f):
    return f.status in ("FILED", "FILED_PAID")


def completed_on(f):
    return f.payment_date or f.filed_on or (f.updated_at.date() if is_complete(f) else None)


def filing_state(f, today=None):
    today = today or timezone.localdate()
    done = is_complete(f)
    done_on = completed_on(f)
    return {"is_complete": done, "is_overdue": (not done) and f.due_date < today,
            "days_left": None if done else (f.due_date - today).days,
            "paid_late": bool(done and done_on and done_on > f.due_date)}


def filing_defaults(ftype, reg, description=None):
    code = {"PF_ECR": "PF-ECR", "ESIC": "ESIC", "TDS_24Q": "TDS-24Q", "LWF": "LWF"}.get(ftype)
    if ftype == "PT":
        code = f"PT-{reg.state_code}" if reg is not None and reg.state_code else "PT"
    desc = description or {"PF_ECR": "EPF Monthly ECR Filing", "ESIC": "ESIC Contribution Return",
                           "TDS_24Q": "TDS Quarterly Return (Form 24Q)",
                           "LWF": "Labour Welfare Fund Contribution",
                           "PT": f"{reg.state} Professional Tax" if reg is not None and reg.state else
                           "Professional Tax"}.get(ftype)
    return code, desc


# ---------------- coverage (employees) ----------------
def active_employees(company):
    return employees_qs(company).filter(is_active=True)


def pf_members(company):
    return active_employees(company).filter(
        (Q(pf_number__isnull=False) & ~Q(pf_number="")) | Q(PF_Percentage__gt=0))


def esi_members(company):
    return active_employees(company).filter(
        (Q(esi_number__isnull=False) & ~Q(esi_number="")) | Q(ESI_Percentage__gt=0))


def uan_count(qs):
    return qs.filter(people_profile__uan_number__isnull=False).exclude(people_profile__uan_number="").count()


# ---------------- payroll aggregation (read only) ----------------
def payroll_by_month(company, pairs):
    """{(year, month): {employees, gross, pf, esi, tds}} for the given (year, month) pairs."""
    if not pairs:
        return {}
    cond = Q()
    for y, m in pairs:
        cond |= Q(year=y, month=m)
    rows = (Payroll.objects.filter(company=company, is_active=True).filter(cond).values("year", "month")
            .annotate(n=Count("id"), gross=Sum("gross_salary"), pf=Sum("PF_deduction"), esi=Sum("ESI_deduction"),
                      tds=Sum("TDS_deduction")))
    return {(r["year"], r["month"]): {"employees": r["n"], "gross": float(r["gross"] or 0),
                                      "pf": float(r["pf"] or 0), "esi": float(r["esi"] or 0),
                                      "tds": float(r["tds"] or 0)} for r in rows}


def last_months(n, today=None):
    t = today or timezone.localdate()
    y, m, out = t.year, t.month, []
    for _ in range(n):
        out.append((y, m))
        y, m = (y - 1, 12) if m == 1 else (y, m - 1)
    return out


# ---------------- licences ----------------
def license_state(l, today=None):
    today = today or timezone.localdate()
    if l.valid_until is None:
        return "ACTIVE", None
    left = (l.valid_until - today).days
    if left < 0:
        return "EXPIRED", left
    return ("EXPIRING" if left <= (l.reminder_days or 0) else "ACTIVE"), left


# ---------------- alerts (computed live) ----------------
SEV_ORDER = {"CRITICAL": 0, "WARNING": 1, "INFO": 2}


def build_alerts(company, days=30, today=None):
    today = today or timezone.localdate()
    out = []

    def add(kind, sev, message, due, ref_type, ref_id):
        out.append({"kind": kind, "severity": sev, "message": message, "due_date": iso(due),
                    "days_left": (due - today).days if due else None, "ref": {"type": ref_type, "id": ref_id}})

    for f in ComplianceFiling.objects.filter(company=company, is_active=True).exclude(
            status__in=["FILED", "FILED_PAID"]):
        left = (f.due_date - today).days
        what = f.description + (f" for {month_label(f.period_month, f.period_year)} wage cycle"
                                if f.period_month else (f" for Q{f.quarter} FY {f.financial_year}" if f.quarter else ""))
        if left < 0:
            add("FILING_OVERDUE", "CRITICAL", f"OVERDUE by {-left} day(s): {what}.", f.due_date, "filing", f.id)
        elif left <= days:
            noun = "day" if left == 1 else "days"
            add("FILING_DUE", "WARNING" if left <= 7 else "INFO",
                f"{left} {noun} remaining to finalize {what}." if left else f"Due today: {what}.",
                f.due_date, "filing", f.id)
    for l in LabourLicense.objects.filter(company=company, is_active=True, valid_until__isnull=False):
        st, left = license_state(l, today)
        label = dict(LabourLicense.TYPES).get(l.license_type)
        where = f" ({l.branch.name})" if l.branch_id else ""
        if st == "EXPIRED":
            add("LICENSE_EXPIRED", "CRITICAL", f"{label}{where} licence {l.license_number} expired {-left} day(s) ago.",
                l.valid_until, "license", l.id)
        elif st == "EXPIRING" and left <= max(days, l.reminder_days or 0):
            add("LICENSE_EXPIRING", "WARNING", f"{label}{where} licence {l.license_number} expires in {left} day(s).",
                l.valid_until, "license", l.id)
    for r in ComplianceRegistration.objects.filter(company=company, is_active=True, valid_until__isnull=False):
        left = (r.valid_until - today).days
        label = dict(ComplianceRegistration.TYPES).get(r.reg_type)
        if left < 0:
            add("REGISTRATION_EXPIRED", "CRITICAL", f"{label} {r.number} expired {-left} day(s) ago.", r.valid_until,
                "registration", r.id)
        elif left <= days:
            add("REGISTRATION_EXPIRING", "WARNING", f"{label} {r.number} is valid for {left} more day(s).",
                r.valid_until, "registration", r.id)
    for i in LabourInspection.objects.filter(company=company, is_active=True, status="OPEN").exclude(
            outcome="COMPLIANT"):
        left = (i.action_due_date - today).days if i.action_due_date else None
        if left is not None and left < 0:
            add("INSPECTION_ACTION_OVERDUE", "CRITICAL",
                f"Inspection of {i.inspection_date:%d %b %Y}: corrective action overdue by {-left} day(s).",
                i.action_due_date, "inspection", i.id)
        elif left is None or left <= days:
            add("INSPECTION_OPEN", "WARNING", f"Inspection of {i.inspection_date:%d %b %Y} has open observations.",
                i.action_due_date, "inspection", i.id)
    for r in ComplianceReminder.objects.filter(company=company, is_active=True, is_done=False):
        left = (r.due_date - today).days if r.due_date else None
        if left is None or left <= days:
            add("REMINDER", r.severity, r.title + (f": {r.message}" if r.message else ""), r.due_date, "reminder",
                r.id)
    out.sort(key=lambda a: (SEV_ORDER[a["severity"]], a["days_left"] if a["days_left"] is not None else 10 ** 6))
    return out
