# ============================================================
# Companies & Legal Entities / Organization Units / Master Data Catalog
#   /api/admin-center/legal-entities/   /org-units/   /master-data/
# ============================================================
from zoneinfo import ZoneInfo

from django.db.models import Count
from rest_framework.decorators import action

from Employee.models import Department, EmployeeDT
from People.models import Branch

from .common import AuditedCrud, emp_brief, emp_by_code, err, ok, to_bool, to_int
from .models import LegalEntity, MasterDataValue, OrgUnit


# ---------------- legal entities ----------------
def legal_row(e):
    return {"id": e.id, "entity_name": e.name, "name": e.name, "code": e.code, "legal_tax_identifier": e.tax_id, "tax_id": e.tax_id,
            "country": e.country, "currency": e.currency, "timezone": e.timezone, "address": e.address,
            "is_primary": e.is_primary, "status": e.status, "created_at": e.created_at.isoformat()}


class LegalEntityViewSet(AuditedCrud):
    """
    CRUD   /api/admin-center/legal-entities/        ?status= ?search=
    POST   {name, code, tax_id?, country?, currency?(3 letters), timezone?(IANA), address?, is_primary?, status?}
    """
    model, code, module_label = LegalEntity, "LEGAL_ENTITY", "Companies"
    search_fields = ("name", "code", "tax_id", "country")
    unique_fields = ("code",)

    def build(self, e):
        return legal_row(e)

    def apply(self, e, d, creating):
        name = (d.get("name") or e.name or "").strip()
        code = (d.get("code") or e.code or "").strip().upper()
        if not name or not code:
            raise ValueError("name and code are required.")
        e.name, e.code = name, code
        self.dup(e, code=code)
        self.dup(e, name=name)
        for k in ("tax_id", "country", "address"):
            if k in d:
                setattr(e, k, d[k])
        if "currency" in d:
            c = (d["currency"] or "").strip().upper()
            if c and (len(c) != 3 or not c.isalpha()):
                raise ValueError("currency must be a 3-letter code such as INR.")
            e.currency = c or None
        if "timezone" in d and d["timezone"]:
            try:
                ZoneInfo(d["timezone"])
            except Exception:
                raise ValueError("timezone must be a valid IANA name such as Asia/Kolkata.")
            e.timezone = d["timezone"]
        if "status" in d:
            if d["status"] not in ("Active", "Inactive"):
                raise ValueError("status must be Active or Inactive.")
            e.status = d["status"]
        if "is_primary" in d:
            e.is_primary = to_bool(d["is_primary"])
        elif creating and not LegalEntity.objects.filter(company=self.company(), is_active=True).exists():
            e.is_primary = True

    def after_save(self, e, creating):
        if e.is_primary:
            LegalEntity.objects.filter(company=e.company, is_active=True).exclude(pk=e.pk).update(is_primary=False)

    def before_delete(self, e):
        if e.is_primary and LegalEntity.objects.filter(company=e.company, is_active=True).exclude(pk=e.pk).exists():
            raise ValueError("The primary entity cannot be deleted while other entities exist. Make another entity primary first.")


# ---------------- organization units ----------------
def org_row(u, request=None):
    return {"id": u.id, "unit_type": u.unit_type, "name": u.name, "unit_name": u.name, "code": u.code,
            "parent_id": u.parent_id, "parent_structure": u.parent.name if u.parent_id else u.parent_name,
            "head": emp_brief(u.head, request) if u.head_id else None, "head_manager": u.head.name if u.head_id else None,
            "status": u.status, "department_id": u.department_id, "branch_id": u.branch_id, "created_at": u.created_at.isoformat()}


def sync_org_units(company, actor=None):
    """Existing Departments / Branches appear as units automatically (linked, never copied)."""
    for d in Department.objects.filter(company=company, is_active=True, ).exclude(pk__in=OrgUnit.objects.filter(company=company, department__isnull=False).values("department_id")):
        if not OrgUnit.objects.filter(company=company, unit_type="Department", name__iexact=d.name, is_active=True).exists():
            OrgUnit.objects.create(company=company, unit_type="Department", name=d.name, code=d.code, department=d, created_by=actor, updated_by=actor)
    for b in Branch.objects.filter(company=company, is_active=True).exclude(pk__in=OrgUnit.objects.filter(company=company, branch__isnull=False).values("branch_id")):
        if not OrgUnit.objects.filter(company=company, unit_type="Location", name__iexact=b.name, is_active=True).exists():
            OrgUnit.objects.create(company=company, unit_type="Location", name=b.name, code=b.code, branch=b, created_by=actor, updated_by=actor)


class OrgUnitViewSet(AuditedCrud):
    """
    CRUD   /api/admin-center/org-units/       ?unit_type= ?status= ?search= ?parent=<id>
    POST   {unit_type: Department|Business Unit|Division|Location|Region, name, code?, parent?(id), parent_name?, head_employee_code?, status?}
    Department / Location units are LINKED to the existing Employee.Department / People.Branch rows (created if missing, kept in sync).
    POST   /api/admin-center/org-units/sync/   pull existing Departments + Branches in
    """
    model, code, module_label = OrgUnit, "ORG_UNIT", "Organization"
    status_field = "status"
    select = ("parent", "head", "department", "branch")
    search_fields = ("name", "code", "parent_name")
    unique_fields = ("name",)
    permission_action_map = {"sync": "create"}
    sensitive = False

    def build(self, u):
        return org_row(u, self.request)

    def filter(self, qs, p):
        qs = super().filter(qs, {k: v for k, v in p.items() if k != "employee"})
        if p.get("unit_type"):
            qs = qs.filter(unit_type=p["unit_type"])
        if str(p.get("parent") or "").isdigit():
            qs = qs.filter(parent_id=int(p["parent"]))
        return qs

    def list(self, request):
        sync_org_units(self.company(), self.actor())
        return super().list(request)

    @action(detail=False, methods=["post"], url_path="sync")
    def sync(self, request):
        before = OrgUnit.objects.filter(company=self.company()).count()
        sync_org_units(self.company(), self.actor())
        return ok("ORG_UNITS_SYNCED", "Existing departments and locations synced.", {"added": OrgUnit.objects.filter(company=self.company()).count() - before})

    def apply(self, u, d, creating):
        co = self.company()
        if creating and d.get("unit_type") not in dict(OrgUnit.TYPES):
            raise ValueError(f"unit_type must be one of: {', '.join(dict(OrgUnit.TYPES))}.")
        if not creating and "unit_type" in d and d["unit_type"] != u.unit_type:
            raise ValueError("unit_type cannot be changed.")
        if creating:
            u.unit_type = d["unit_type"]
        name = (d.get("name") or u.name or "").strip()
        if not name:
            raise ValueError("name is required.")
        u.name = name
        self.dup(u, unit_type=u.unit_type, name=name)
        if "code" in d:
            u.code = (d["code"] or None) and d["code"].strip().upper()
        if "parent" in d:
            if d["parent"] in (None, ""):
                u.parent = None
            else:
                p = OrgUnit.objects.filter(company=co, pk=to_int(d["parent"]), is_active=True).first()
                if p is None:
                    raise ValueError("parent unit not found.")
                x = p
                while x is not None:
                    if u.pk and x.pk == u.pk:
                        raise ValueError("A unit cannot be its own parent / ancestor.")
                    x = x.parent
                u.parent = p
        if "parent_name" in d:
            u.parent_name = d["parent_name"]
        if "head_employee_code" in d:
            u.head = emp_by_code(co, d["head_employee_code"], required=False) if d["head_employee_code"] else None
        if "status" in d:
            if d["status"] not in ("Active", "Inactive"):
                raise ValueError("status must be Active or Inactive.")
            u.status = d["status"]

    def after_save(self, u, creating):
        co = u.company
        if u.unit_type == "Department":
            dep = u.department or Department.objects.filter(company=co, name__iexact=u.name).first()
            if dep is None:
                dep = Department.objects.create(company=co, name=u.name, code=u.code, created_by=u.updated_by, updated_by=u.updated_by)
            else:
                dep.name, dep.code = u.name, u.code
                dep.save()
            if u.department_id != dep.id:
                OrgUnit.objects.filter(pk=u.pk).update(department=dep)
                u.department = dep
        elif u.unit_type == "Location":
            br = u.branch or Branch.objects.filter(company=co, name__iexact=u.name).first()
            if br is None:
                br = Branch.objects.create(company=co, name=u.name, code=u.code, created_by=u.updated_by, updated_by=u.updated_by)
            else:
                br.name, br.code = u.name, u.code
                br.save()
            if u.branch_id != br.id:
                OrgUnit.objects.filter(pk=u.pk).update(branch=br)
                u.branch = br

    def before_delete(self, u):
        if u.children.filter(is_active=True).exists():
            raise ValueError("This unit has child units. Move or delete them first.")
        if u.department_id and EmployeeDT.objects.filter(company=u.company, department_id=u.department_id, is_active=True).exists():
            raise ValueError("Employees are still assigned to this department. Reassign them first.")
        if u.branch_id:
            from People.models import EmployeeExtra
            if EmployeeExtra.objects.filter(company=u.company, branch_id=u.branch_id, employee__is_active=True).exists():
                raise ValueError("Employees are still assigned to this location. Reassign them first.")

    def after_delete(self, u):
        if u.department_id:
            Department.objects.filter(pk=u.department_id).update(is_active=False)
        if u.branch_id:
            Branch.objects.filter(pk=u.branch_id).update(is_active=False)


# ---------------- master data ----------------
def master_row(m):
    return {"id": m.id, "category": m.category, "master_value": m.value, "value": m.value, "code": m.code, "sort_order": m.sort_order,
            "status": m.status, "created_at": m.created_at.isoformat()}


class MasterDataViewSet(AuditedCrud):
    """
    CRUD   /api/admin-center/master-data/          ?category= ?status= ?search=
    POST   {category, value, code, sort_order?, status?}
    GET    /api/admin-center/master-data/categories/     categories with counts
    """
    model, code, module_label = MasterDataValue, "MASTER_DATA", "Master Data"
    ref_field = "value"
    search_fields = ("category", "value", "code")
    unique_fields = ("code",)
    permission_action_map = {"categories": "view"}
    sensitive = False

    def build(self, m):
        return master_row(m)

    def filter(self, qs, p):
        qs = super().filter(qs, {k: v for k, v in p.items() if k != "employee"})
        return qs.filter(category__iexact=p["category"]) if p.get("category") else qs

    def apply(self, m, d, creating):
        cat = (d.get("category") or m.category or "").strip()
        val = (d.get("value") or m.value or "").strip()
        code = (d.get("code") or m.code or "").strip().upper()
        if not cat or not val or not code:
            raise ValueError("category, value and code are required.")
        m.category, m.value, m.code = cat, val, code
        self.dup(m, category=cat, code=code)
        self.dup(m, category=cat, value=val)
        if "sort_order" in d:
            s = to_int(d["sort_order"])
            if s is None or s < 0:
                raise ValueError("sort_order must be 0 or more.")
            m.sort_order = s
        elif creating:
            m.sort_order = MasterDataValue.objects.filter(company=self.company(), category__iexact=cat, is_active=True).count() + 1
        if "status" in d:
            if d["status"] not in ("Active", "Inactive"):
                raise ValueError("status must be Active or Inactive.")
            m.status = d["status"]

    @action(detail=False, methods=["get"], url_path="categories")
    def categories(self, request):
        q = (MasterDataValue.objects.filter(company=self.company(), is_active=True).values("category")
             .annotate(total=Count("id")).order_by("category"))
        return ok("MASTER_CATEGORIES", "Master data categories.", [{"category": r["category"], "values": r["total"]} for r in q])
