# ============================================================
# 5. EMPLOYEE ASSETS
#   /api/people/assets/            asset master (Asset Master Management)
#   /api/people/asset-allocations/ assigned assets & custody (the table in the UI)
# ============================================================
import csv
from datetime import timedelta

from django.db import transaction
from django.db.models import Q, Sum
from django.http import HttpResponse
from django.utils import timezone
from rest_framework.decorators import action
from rest_framework.viewsets import ViewSet

from .common import (CrudBase, PeopleAuthMixin, dept_name, emp_brief, emp_by_code, employees_qs, err, iso, ok,
                     paginate, to_bool, to_date, to_decimal)
from .models import AssetAllocation, AssetAudit, AssetMaintenance, AssetMaster, ExitClearance

# ------------------------------------------------------------
# Shared helpers (used by the Master / Allocation / Return / History tabs)
# No data is hard-coded: everything below reads the existing People models.
# ------------------------------------------------------------
ACTIVE_EXIT = ("Initiated", "In Progress", "Cleared")          # same set views_directory uses for "exit in progress"
RETURN_ASSET_STATUS = ("Available", "Under Repair", "Retired", "Lost")
ASSET_CONDITIONS = ("Brand New", "Good", "Fair", "Needs Repair", "Damaged")   # dropdown values (condition is free text on the model)


def active_exit(emp):
    """The employee's running ExitClearance (offboarding), or None."""
    return (ExitClearance.objects.filter(employee=emp, is_active=True, status__in=ACTIVE_EXIT)
            .order_by("-id").first())


def open_allocation(asset):
    return asset.allocations.filter(status="Allocated", is_active=True).select_related("employee").first()


def return_is_pending(al):
    """Return is pending when HR requested it OR the custodian is in an exit process (departmental clearance)."""
    return bool(al.return_pending or active_exit(al.employee) is not None)


def find_asset(company, ref, qs=None):
    """Resolve an asset by asset_tag (AST-MBP-0142) or numeric id inside the company."""
    qs = qs if qs is not None else AssetMaster.objects.filter(company=company, is_active=True)
    ref = str(ref or "").strip()
    if not ref:
        return None
    hit = qs.filter(asset_tag__iexact=ref).first()
    if hit is None and ref.isdigit():
        hit = qs.filter(pk=int(ref)).first()
    return hit


def assignable_employee(company, code):
    emp = emp_by_code(company, code)
    if active_exit(emp) is not None:
        raise ValueError(f"{emp.name} ({emp.employee_code}) is in an exit process; assets cannot be assigned.")
    return emp


def do_allocate(company, asset, emp, d, actor):
    """Create the allocation row and flip the asset to Allocated (clears any reservation)."""
    al = AssetAllocation.objects.create(
        company=company, asset=asset, employee=emp, allocated_on=to_date(d.get("allocated_on")) or timezone.localdate(),
        expected_return=to_date(d.get("expected_return")), condition_out=d.get("condition_out"),
        notes=d.get("notes"), created_by=actor, updated_by=actor)
    asset.status, asset.reserved_for, asset.reserved_on, asset.updated_by = "Allocated", None, None, actor
    asset.save()
    return al


def return_date(d, allocated_on):
    """Actual return date from the form (returned_on). Defaults to today; cannot be future or before allocation."""
    when = to_date(d.get("returned_on")) or timezone.localdate()
    if when > timezone.localdate():
        raise ValueError("Return date cannot be in the future.")
    if allocated_on and when < allocated_on:
        raise ValueError("Return date cannot be before the allocation date.")
    return when


def return_asset_status(d):
    """Where the asset goes after it is received back. Only the RETURN_ASSET_STATUS values are accepted."""
    status = d.get("asset_status") or "Available"
    if status not in RETURN_ASSET_STATUS:
        raise ValueError(f"Invalid asset_status. Allowed: {', '.join(RETURN_ASSET_STATUS)}")
    return status


def append_note(existing, text, when):
    """Allocation remarks are never overwritten by a return: return remarks are appended with their date."""
    if not text:
        return existing
    line = f"[Return {when.isoformat()}] {text}"
    return f"{existing}\n{line}" if existing else line


def register_asset(company, data, actor):
    """Create one inventory row from the Allocate form. Same rules as POST /assets/ (unique tag and serial)."""
    tag = (data.get("asset_tag") or "").strip()
    name = (data.get("device_name") or "").strip()
    category = data.get("category") or "Hardware"
    serial = (data.get("serial_number") or "").strip() or None
    if not tag or not name:
        raise ValueError("A new asset needs asset_tag and device_name.")
    if category not in dict(AssetMaster.CATEGORY):
        raise ValueError(f"Invalid category. Allowed: {', '.join(dict(AssetMaster.CATEGORY))}")
    if AssetMaster.objects.filter(company=company, is_active=True, asset_tag__iexact=tag).exists():
        raise ValueError("Asset tag already exists.")
    if serial and AssetMaster.objects.filter(company=company, is_active=True, serial_number__iexact=serial).exists():
        raise ValueError("Serial number already exists.")
    return AssetMaster.objects.create(
        company=company, asset_tag=tag, device_name=name, category=category, serial_number=serial,
        vendor=(data.get("vendor") or None), purchase_date=to_date(data.get("purchase_date")),
        purchase_cost=to_decimal(data.get("purchase_cost")), warranty_until=to_date(data.get("warranty_until")),
        notes=data.get("notes") or None, status="Available", created_by=actor, updated_by=actor)


def do_close(al, d, actor, asset_status="Available"):
    """Close an open allocation (return). asset_status is where the asset goes afterwards."""
    when = return_date(d, al.allocated_on)
    al.status, al.returned_on, al.return_pending = "Returned", when, False
    if d.get("condition_in") is not None:
        al.condition_in = d.get("condition_in")
    al.notes = append_note(al.notes, d.get("notes"), when)
    al.updated_by = actor
    al.save()
    al.asset.status = asset_status if asset_status in RETURN_ASSET_STATUS + ("Allocated",) else "Available"
    al.asset.updated_by = actor
    al.asset.save()
    return al


def csv_safe(v):
    """Stop CSV/Excel formula injection."""
    v = "" if v is None else str(v)
    return "'" + v if v[:1] in ("=", "+", "-", "@") else v


def lifecycle_events(company, asset=None, limit=100):
    """One merged lifecycle log: allocations, returns, audits and maintenance (newest first)."""
    ev = []
    al_qs = AssetAllocation.objects.filter(company=company, is_active=True).select_related("asset", "employee")
    au_qs = AssetAudit.objects.filter(company=company, is_active=True).select_related("asset")
    mt_qs = AssetMaintenance.objects.filter(company=company, is_active=True).select_related("asset")
    if asset is not None:
        al_qs, au_qs, mt_qs = al_qs.filter(asset=asset), au_qs.filter(asset=asset), mt_qs.filter(asset=asset)
    for a in al_qs:
        who = f"{a.employee.name} ({a.employee.employee_code})"
        ev.append({"date": a.allocated_on, "ts": a.created_at, "type": "ALLOCATED", "asset_tag": a.asset.asset_tag,
                   "title": f"Allocated to {who}", "description": a.condition_out, "by": a.created_by,
                   "ref_id": a.id})
        if a.returned_on:
            ev.append({"date": a.returned_on, "ts": a.updated_at, "type": "RETURNED", "asset_tag": a.asset.asset_tag,
                       "title": f"Returned by {who}", "description": a.condition_in, "by": a.updated_by,
                       "ref_id": a.id})
    for x in au_qs:
        ev.append({"date": x.audited_on, "ts": x.created_at, "type": "AUDIT", "asset_tag": x.asset.asset_tag,
                   "title": "Audit - OK" if x.is_ok else "Audit - ISSUE FOUND", "description": x.notes or x.condition,
                   "by": x.audited_by, "ref_id": x.id})
    for m in mt_qs:
        ev.append({"date": m.event_date, "ts": m.created_at, "type": "MAINTENANCE", "asset_tag": m.asset.asset_tag,
                   "title": f"{m.event_type} ({m.status})", "description": m.description, "by": m.created_by,
                   "ref_id": m.id})
    ev.sort(key=lambda e: (e["date"], e["ts"]), reverse=True)
    return [{**{k: v for k, v in e.items() if k not in ("date", "ts")}, "date": iso(e["date"])} for e in ev[:limit]]


class AssetMasterViewSet(CrudBase):
    """CRUD on the asset catalogue. ?status= ?category= ?search="""
    model = AssetMaster
    code = "ASSET"
    search_fields = ("asset_tag", "device_name", "serial_number", "vendor")
    select = ("reserved_for",)

    def build(self, a):
        cur = a.allocations.filter(status="Allocated", is_active=True).select_related("employee").first()
        data = {"id": a.id, "asset_tag": a.asset_tag, "device_name": a.device_name, "category": a.category,
                "serial_number": a.serial_number, "purchase_date": iso(a.purchase_date),
                "purchase_cost": float(a.purchase_cost) if a.purchase_cost is not None else None,
                "status": a.status, "notes": a.notes, "current_custodian": emp_brief(cur.employee) if cur else None}
        # ---- Asset Master / Allocation table columns (dynamic) ----
        pending = bool(cur and return_is_pending(cur))
        if cur:
            assigned_to, display = cur.employee.name, ("Assigned (Return Pending)" if pending else "Assigned")
        elif a.status == "Reserved" and a.reserved_for_id:
            assigned_to, display = None, "Reserved"
        else:
            assigned_to, display = None, a.status
        label = (assigned_to if assigned_to else
                 f"-- (Reserved for {a.reserved_for.name})" if a.status == "Reserved" and a.reserved_for_id else "--")
        today = timezone.localdate()
        data.update({"vendor": a.vendor, "warranty_until": iso(a.warranty_until),
                     "warranty_status": (None if not a.warranty_until else "Expired" if a.warranty_until < today else "Active"),
                     "assigned_to": assigned_to, "assigned_to_label": label, "display_status": display,
                     "current_allocation_id": cur.id if cur else None, "return_pending": pending,
                     "reserved_for": emp_brief(a.reserved_for) if a.reserved_for_id else None,
                     "reserved_on": iso(a.reserved_on),
                     "available_actions": (["reassign", "request_return"] if cur else
                                           ["assign", "unreserve"] if a.status == "Reserved" else
                                           ["assign", "reserve"] if a.status == "Available" else [])})
        return data

    def filter(self, qs, p):
        qs = super().filter(qs, p)
        return qs.filter(category=p["category"]) if p.get("category") else qs

    def apply(self, a, d, creating):
        tag = (d.get("asset_tag") or a.asset_tag or "").strip()
        name = (d.get("device_name") or a.device_name or "").strip()
        if not tag or not name:
            raise ValueError("asset_tag and device_name are required.")
        # ---- additive guards: no duplicate serial, keep status consistent with allocations/reservations ----
        serial = (d.get("serial_number") or "").strip() if "serial_number" in d else None
        if serial and AssetMaster.objects.filter(company=self.company(), is_active=True,
                                                 serial_number__iexact=serial).exclude(pk=a.pk).exists():
            raise ValueError("Serial number already exists.")
        if "status" in d and d["status"] != a.status:
            if d["status"] == "Reserved":
                raise ValueError("Use the reserve action to reserve an asset.")
            if a.pk and a.status == "Allocated" and a.allocations.filter(status="Allocated", is_active=True).exists():
                raise ValueError("Asset is currently allocated. Return it first.")
        if AssetMaster.objects.filter(company=self.company(), asset_tag__iexact=tag).exclude(pk=a.pk).exists():
            raise ValueError("Asset tag already exists.")
        a.asset_tag, a.device_name = tag, name
        if "category" in d:
            if d["category"] not in dict(AssetMaster.CATEGORY):
                raise ValueError(f"Invalid category. Allowed: {', '.join(dict(AssetMaster.CATEGORY))}")
            a.category = d["category"]
        if "status" in d:
            if d["status"] not in dict(AssetMaster.STATUS):
                raise ValueError(f"Invalid status. Allowed: {', '.join(dict(AssetMaster.STATUS))}")
            if d["status"] == "Allocated" and not a.allocations.filter(status="Allocated").exists():
                raise ValueError("Use the allocate action to allocate an asset.")
            a.status = d["status"]
        for k in ("serial_number", "notes"):
            if k in d:
                setattr(a, k, d[k])
        if "purchase_date" in d:
            a.purchase_date = to_date(d["purchase_date"])
        if "purchase_cost" in d:
            a.purchase_cost = to_decimal(d["purchase_cost"])
        if "vendor" in d:
            a.vendor = d["vendor"]
        if "warranty_until" in d:
            a.warranty_until = to_date(d["warranty_until"])
        if a.status != "Reserved":                       # reservation only lives while status == Reserved
            a.reserved_for, a.reserved_on = None, None

    def destroy(self, request, pk=None):
        a = self.scope().filter(pk=pk).first()
        if a is not None and a.allocations.filter(status="Allocated", is_active=True).exists():
            return err("IN_USE", "Asset is currently allocated. Return it first.", 409)
        return super().destroy(request, pk)

    # ------------------------------------------------------------------
    # Asset Master / Asset Allocation tabs - extra endpoints
    # ------------------------------------------------------------------
    @action(detail=False, methods=["get"])
    def summary(self, request):
        """GET /api/people/assets/summary/  - counters for the header / cards."""
        qs = self.scope().filter(is_active=True)
        today = timezone.localdate()
        by_status = {k: qs.filter(status=k).count() for k, _ in AssetMaster.STATUS}
        by_category = {k: qs.filter(category=k).count() for k, _ in AssetMaster.CATEGORY}
        open_al = AssetAllocation.objects.filter(company=self.company(), is_active=True, status="Allocated")
        exit_emp = ExitClearance.objects.filter(company=self.company(), is_active=True,
                                                status__in=ACTIVE_EXIT).values("employee_id")
        return ok("ASSET_SUMMARY", "Asset summary.", {
            "total": qs.count(), "by_status": by_status, "by_category": {k: v for k, v in by_category.items() if v},
            "return_pending": open_al.filter(Q(return_pending=True) | Q(employee_id__in=exit_emp)).count(),
            "warranty_expired": qs.filter(warranty_until__lt=today).count(),
            "warranty_expiring_60d": qs.filter(warranty_until__gte=today, warranty_until__lte=today + timedelta(days=60)).count(),
            "total_purchase_cost": float(qs.aggregate(t=Sum("purchase_cost"))["t"] or 0)})

    @action(detail=False, methods=["get"])
    def options(self, request):
        """GET /api/people/assets/options/  - dropdown data for the Register / Assign forms."""
        c = self.company()
        return ok("ASSET_OPTIONS", "Dropdown data.", {
            "categories": [{"code": k, "label": v} for k, v in AssetMaster.CATEGORY],
            "statuses": [{"code": k, "label": v} for k, v in AssetMaster.STATUS],
            "return_asset_statuses": list(RETURN_ASSET_STATUS),
            "conditions": list(ASSET_CONDITIONS),
            "maintenance_event_types": [{"code": k, "label": v} for k, v in AssetMaintenance.EVENT],
            "maintenance_statuses": [{"code": k, "label": v} for k, v in AssetMaintenance.STATUS],
            "employees": [{"employee_code": e.employee_code, "name": e.name, "designation": e.Designation,
                           "department": dept_name(e), "in_exit": active_exit(e) is not None}
                          for e in employees_qs(c)]})

    @action(detail=False, methods=["get"])
    def export(self, request):
        """GET /api/people/assets/export/?status=&category=&search=   -> CSV download ("Export CSV" button)."""
        rows = self.filter(self.scope().filter(is_active=True), request.query_params)
        resp = HttpResponse(content_type="text/csv; charset=utf-8")
        resp["Content-Disposition"] = f'attachment; filename="asset_inventory_{timezone.localdate().isoformat()}.csv"'
        w = csv.writer(resp)
        w.writerow(["Asset Tag", "Asset Specification", "Category", "Serial No.", "Assigned To", "Employee Code",
                    "Status", "Vendor", "Purchase Date", "Purchase Cost", "Warranty Until"])
        for a in rows:
            b = self.build(a)
            cust = b["current_custodian"]
            who = (b["assigned_to"] or (f"Reserved for {b['reserved_for']['name']}" if b["reserved_for"] else ""))
            w.writerow([csv_safe(x) for x in (
                a.asset_tag, a.device_name, a.category, a.serial_number, who,
                cust["employee_code"] if cust else "", b["display_status"], a.vendor, iso(a.purchase_date),
                a.purchase_cost, iso(a.warranty_until))])
        return resp

    def _asset(self, pk):
        qs = self.model.objects.filter(company=self.company(), pk=pk, is_active=True)
        if transaction.get_connection().in_atomic_block:      # reserve / assign / reassign: lock the row
            qs = qs.select_for_update()
        return qs.first()

    @action(detail=True, methods=["post"])
    @transaction.atomic
    def reserve(self, request, pk=None):
        """POST /assets/<id>/reserve/  {employee_code, reserved_on?}  - hold an Available asset for a (new) joiner."""
        a = self._asset(pk)
        if a is None:
            return err("NOT_FOUND", "Asset not found.", 404)
        if a.status != "Available":
            return err("NOT_AVAILABLE", f"Only Available assets can be reserved (current status: {a.status}).", 409)
        try:
            emp = emp_by_code(self.company(), request.data.get("employee_code"))
            a.reserved_on = to_date(request.data.get("reserved_on")) or timezone.localdate()
        except ValueError as e:
            return err("VALIDATION", str(e))
        a.status, a.reserved_for, a.updated_by = "Reserved", emp, self.actor()
        a.save()
        return ok("ASSET_RESERVED", f"Asset reserved for {emp.name}.", self.build(a))

    @action(detail=True, methods=["post"])
    @transaction.atomic
    def unreserve(self, request, pk=None):
        """POST /assets/<id>/unreserve/  - release the reservation, asset becomes Available again."""
        a = self._asset(pk)
        if a is None:
            return err("NOT_FOUND", "Asset not found.", 404)
        if a.status != "Reserved":
            return err("NOT_RESERVED", "Asset is not reserved.", 409)
        a.status, a.reserved_for, a.reserved_on, a.updated_by = "Available", None, None, self.actor()
        a.save()
        return ok("ASSET_UNRESERVED", "Reservation released.", self.build(a))

    @action(detail=True, methods=["post"])
    @transaction.atomic
    def assign(self, request, pk=None):
        """POST /assets/<id>/assign/  {employee_code, allocated_on?, expected_return?, condition_out?, notes?, force?}
        Row "Assign" button. Allowed for Available assets, or Reserved ones (reserved employee, or force=true)."""
        a = self._asset(pk)
        if a is None:
            return err("NOT_FOUND", "Asset not found.", 404)
        d = request.data
        try:
            if a.status not in ("Available", "Reserved"):
                raise ValueError(f"Asset cannot be assigned (current status: {a.status})."
                                 + (" Use reassign." if a.status == "Allocated" else ""))
            emp = assignable_employee(self.company(), d.get("employee_code"))
            if a.status == "Reserved" and a.reserved_for_id != emp.id and not to_bool(d.get("force")):
                raise ValueError(f"Asset is reserved for {a.reserved_for.name if a.reserved_for_id else 'someone else'}. "
                                 "Pass force=true to override.")
            al = do_allocate(self.company(), a, emp, d, self.actor())
        except ValueError as e:
            transaction.set_rollback(True)
            return err("VALIDATION", str(e))
        return ok("ASSET_ASSIGNED", f"Asset assigned to {emp.name}.",
                  {"asset": self.build(a), "allocation": AllocationViewSet().build(al)}, 201)

    @action(detail=True, methods=["post"])
    @transaction.atomic
    def reassign(self, request, pk=None):
        """POST /assets/<id>/reassign/  {employee_code, condition_in?, condition_out?, notes?, expected_return?}
        Row "Reassign" button: closes the current custody and opens a new one for another employee."""
        a = self._asset(pk)
        if a is None:
            return err("NOT_FOUND", "Asset not found.", 404)
        d = request.data
        try:
            cur = open_allocation(a) if a.status == "Allocated" else None
            if cur is None:
                raise ValueError("Only an allocated asset can be reassigned. Use assign instead.")
            emp = assignable_employee(self.company(), d.get("employee_code"))
            if emp.id == cur.employee_id:
                raise ValueError("Asset is already assigned to this employee.")
            to_date(d.get("allocated_on")), to_date(d.get("expected_return"))          # validate before writing
            old_name = cur.employee.name
            do_close(cur, {"condition_in": d.get("condition_in"),
                          "notes": d.get("reason") or f"Reassigned to {emp.name} ({emp.employee_code})"},
                    self.actor(), asset_status="Allocated")
            new = do_allocate(self.company(), a, emp, d, self.actor())
        except ValueError as e:
            transaction.set_rollback(True)
            return err("VALIDATION", str(e))
        return ok("ASSET_REASSIGNED", f"Asset reassigned from {old_name} to {emp.name}.",
                  {"asset": self.build(a), "previous_allocation": AllocationViewSet().build(cur),
                   "allocation": AllocationViewSet().build(new)}, 201)

    @action(detail=True, methods=["get"])
    def history(self, request, pk=None):
        """GET /assets/<id>/history/  - full lifecycle of one asset (allocations, returns, audits, maintenance)."""
        a = self._asset(pk)
        if a is None:
            return err("NOT_FOUND", "Asset not found.", 404)
        return ok("ASSET_LIFECYCLE", "Asset lifecycle.", {"asset": self.build(a),
                                                          "events": lifecycle_events(self.company(), a, 500)})


class AllocationViewSet(CrudBase):
    """
    GET  /api/people/asset-allocations/                 ?status=Allocated|Returned &employee=<code> &search=
    POST /api/people/asset-allocations/                 allocate {asset_tag|asset_id, employee_code, ...}
    POST /api/people/asset-allocations/<id>/return/     {condition_in?, notes?}
    POST /api/people/asset-allocations/<id>/audit/      {condition?, is_ok?, notes?}   ("Audit" button)
    GET  /api/people/asset-allocations/<id>/audits/
    """
    model = AssetAllocation
    code = "ALLOCATION"
    select = ("asset", "employee", "employee__department")
    search_fields = ("asset__asset_tag", "asset__device_name", "asset__serial_number", "employee__name",
                     "employee__employee_code")

    def build(self, a):
        data = {"id": a.id, "asset_id": a.asset_id, "asset_tag": a.asset.asset_tag,
                "device_name": a.asset.device_name, "category": a.asset.category,
                "assigned_custodian": emp_brief(a.employee), "status": a.status,
                "allocated_on": iso(a.allocated_on), "expected_return": iso(a.expected_return),
                "returned_on": iso(a.returned_on), "condition_out": a.condition_out,
                "condition_in": a.condition_in, "notes": a.notes,
                "last_audit": iso(a.audits.order_by("-audited_on").values_list("audited_on", flat=True).first())}
        data.update({"serial_number": a.asset.serial_number, "return_pending": bool(a.status == "Allocated" and return_is_pending(a)),
                     "return_requested_on": iso(a.return_requested_on), "return_due_date": iso(a.return_due_date),
                     "return_reason": a.return_reason})
        return data

    @transaction.atomic
    def create(self, request):
        """POST /asset-allocations/  {asset_id | asset_tag | new_asset:{...}, employee_code, allocated_on?,
        expected_return?, condition_out?, notes?}. A new_asset is registered in the same transaction."""
        d, company, actor = request.data, self.company(), self.actor()
        try:
            asset = self._resolve_or_register_asset(company, d, actor)
            emp = assignable_employee(company, d.get("employee_code"))
            allocated_on = to_date(d.get("allocated_on")) or timezone.localdate()
            expected = to_date(d.get("expected_return"))
            if expected and expected < allocated_on:
                raise ValueError("Expected return date cannot be before the allocation date.")
            al = AssetAllocation.objects.create(
                company=company, asset=asset, employee=emp, allocated_on=allocated_on, expected_return=expected,
                condition_out=d.get("condition_out"), notes=d.get("notes"), created_by=actor, updated_by=actor)
            asset.status, asset.reserved_for, asset.reserved_on, asset.updated_by = "Allocated", None, None, actor
            asset.save()
        except ValueError as e:
            transaction.set_rollback(True)
            return err("VALIDATION", str(e))
        return ok("ASSET_ALLOCATED", "Asset allocated.", self.build(al), 201)

    @staticmethod
    def _resolve_or_register_asset(company, d, actor):
        """Existing inventory asset (asset_id / asset_tag, row-locked) or a brand-new one. Never duplicates inventory."""
        qs = AssetMaster.objects.select_for_update().filter(company=company, is_active=True)
        if d.get("asset_id"):
            asset = qs.filter(pk=d["asset_id"]).first()
        elif (d.get("asset_tag") or "").strip():
            asset = qs.filter(asset_tag__iexact=d["asset_tag"].strip()).first()
        elif isinstance(d.get("new_asset"), dict):
            asset = register_asset(company, d["new_asset"], actor)
        else:
            raise ValueError("Select an asset from inventory (asset_id) or register a new one (new_asset).")
        if asset is None:
            raise ValueError("Asset not found.")
        if asset.status != "Available":
            raise ValueError(f"Asset is not available (current status: {asset.status}).")
        return asset

    def apply(self, a, d, creating):
        if "expected_return" in d:
            a.expected_return = to_date(d["expected_return"])
            if a.expected_return and a.expected_return < a.allocated_on:
                raise ValueError("Expected return date cannot be before the allocation date.")

    @action(detail=True, methods=["post"], url_path="return")
    @transaction.atomic
    def return_asset(self, request, pk=None):
        """POST /asset-allocations/<id>/return/ {condition_in?, notes?, returned_on?, asset_status?}"""
        a = self.scope().filter(pk=pk).first()
        if a is None:
            return err("NOT_FOUND", "Allocation not found.", 404)
        if a.status == "Returned":
            return err("ALREADY_RETURNED", "Asset is already returned.", 409)
        d = request.data
        try:
            status = return_asset_status(d)
            do_close(a, {"condition_in": d.get("condition_in"), "notes": d.get("notes"),
                         "returned_on": d.get("returned_on")}, self.actor(), status)
        except ValueError as e:
            transaction.set_rollback(True)
            return err("VALIDATION", str(e))
        return ok("ASSET_RETURNED", "Asset returned.", self.build(a))

    @action(detail=True, methods=["post"])
    def audit(self, request, pk=None):
        a = self.scope().filter(pk=pk).first()
        if a is None:
            return err("NOT_FOUND", "Allocation not found.", 404)
        d = request.data
        try:
            when = to_date(d.get("audited_on")) or timezone.localdate()
        except ValueError as e:
            return err("VALIDATION", str(e))
        au = AssetAudit.objects.create(company=a.company, asset=a.asset, allocation=a, audited_on=when,
                                       audited_by=self.actor(), condition=d.get("condition"),
                                       is_ok=str(d.get("is_ok", True)).lower() not in ("false", "0", "no"),
                                       notes=d.get("notes"), created_by=self.actor(), updated_by=self.actor())
        return ok("ASSET_AUDITED", "Audit recorded.", {"id": au.id, "audited_on": iso(au.audited_on),
                                                       "condition": au.condition, "is_ok": au.is_ok}, 201)

    @action(detail=True, methods=["get"])
    def audits(self, request, pk=None):
        a = self.scope().filter(pk=pk).first()
        if a is None:
            return err("NOT_FOUND", "Allocation not found.", 404)
        return ok("ASSET_AUDITS", "Audit trail.", [
            {"id": x.id, "audited_on": iso(x.audited_on), "audited_by": x.audited_by, "condition": x.condition,
             "is_ok": x.is_ok, "notes": x.notes} for x in a.audits.filter(is_active=True)])

    def destroy(self, request, pk=None):
        a = self.scope().filter(pk=pk).first()
        if a is not None and a.status == "Allocated" and a.asset.status == "Allocated":
            a.asset.status, a.asset.updated_by = "Available", self.actor()
            a.asset.save()
        return super().destroy(request, pk)


# ============================================================
# ASSET RETURN tab - "Offboarding Asset Return & Recovery"
#   /api/people/asset-returns/
# Works on the SAME AssetAllocation rows (no extra table). A return is "pending" when HR requested it
# (return_pending=True) OR the custodian has a running ExitClearance (departmental exit clearance).
# ============================================================
class AssetReturnViewSet(PeopleAuthMixin, ViewSet):
    """
    GET  /api/people/asset-returns/                    ?scope=pending|returned  &employee=<code> &search=
    GET  /api/people/asset-returns/<allocation_id>/
    GET  /api/people/asset-returns/by-employee/        pending returns grouped per employee (banner + cards)
    POST /api/people/asset-returns/request/            {employee_code | allocation_id, due_date?, reason?}
    POST /api/people/asset-returns/<allocation_id>/receive/   {condition_in?, asset_status?, notes?, clear_exit_item?}
    POST /api/people/asset-returns/receive-all/        {employee_code, condition_in?, asset_status?, notes?, clear_exit_item?}
    POST /api/people/asset-returns/<allocation_id>/cancel/    withdraw an HR return request
    """
    permission_action_map = {"request_return": "edit", "receive": "edit", "receive_all": "edit", "cancel": "edit"}

    # ---- querysets ----
    def _open(self):
        return (AssetAllocation.objects.filter(company=self.company(), is_active=True, status="Allocated")
                .select_related("asset", "employee", "employee__department"))

    def _exits(self):
        return {x.employee_id: x for x in ExitClearance.objects.filter(
            company=self.company(), is_active=True, status__in=ACTIVE_EXIT).order_by("id")}

    def _pending(self, exits=None):
        exits = self._exits() if exits is None else exits
        return self._open().filter(Q(return_pending=True) | Q(employee_id__in=list(exits.keys())))

    def _row(self, a, exits):
        x = exits.get(a.employee_id) if a.status == "Allocated" else None
        due = a.return_due_date or (x.last_working_day if x else None)
        today = timezone.localdate()
        return {"id": a.id, "asset_id": a.asset_id, "asset_tag": a.asset.asset_tag, "device_name": a.asset.device_name,
                "category": a.asset.category, "serial_number": a.asset.serial_number, "employee": emp_brief(a.employee),
                "status": a.status, "allocated_on": iso(a.allocated_on),
                "return_pending": bool(a.status == "Allocated" and (a.return_pending or x)),
                "source": "EXIT_CLEARANCE" if x else ("HR_REQUEST" if a.return_pending else None),
                "return_requested_on": iso(a.return_requested_on), "return_due_date": iso(due),
                "return_reason": a.return_reason or ("Offboarding - exit clearance" if x else None),
                "overdue": bool(a.status == "Allocated" and due and due < today),
                "exit": ({"id": x.id, "status": x.status, "last_working_day": iso(x.last_working_day),
                          "resignation_date": iso(x.resignation_date)} if x else None),
                "returned_on": iso(a.returned_on), "condition_out": a.condition_out, "condition_in": a.condition_in,
                "notes": a.notes}

    @staticmethod
    def _banner(rows):
        """'1 asset return pending from Vikram Rao (EMP-0504) as part of departmental exit clearance.'"""
        if not rows:
            return "No asset returns pending."
        per = {}
        for r in rows:
            per.setdefault(r["employee"]["employee_code"], []).append(r)
        parts = [f"{len(v)} asset return{'s' if len(v) != 1 else ''} pending from {v[0]['employee']['name']} "
                 f"({k})" for k, v in per.items()]
        tail = " as part of departmental exit clearance." if all(r["source"] == "EXIT_CLEARANCE" for r in rows) else "."
        return "; ".join(parts) + tail

    def _summary(self, rows):
        return {"pending_assets": len(rows), "pending_employees": len({r["employee"]["employee_code"] for r in rows}),
                "overdue": sum(1 for r in rows if r["overdue"]),
                "from_exit_clearance": sum(1 for r in rows if r["source"] == "EXIT_CLEARANCE"),
                "message": self._banner(rows)}

    def _find(self, pk):
        return self._open().filter(pk=pk).first()

    # ---- read ----
    def list(self, request):
        p = request.query_params
        scope = (p.get("scope") or "pending").lower()
        if scope not in ("pending", "returned"):
            return err("VALIDATION", "scope must be 'pending' or 'returned'.")
        exits = self._exits()
        if scope == "pending":
            qs = self._pending(exits)
        else:
            qs = (AssetAllocation.objects.filter(company=self.company(), is_active=True, status="Returned")
                  .select_related("asset", "employee", "employee__department").order_by("-returned_on", "-id"))
        if p.get("employee"):
            qs = qs.filter(employee__employee_code=p["employee"])
        q = (p.get("search") or "").strip()
        if q:
            qs = qs.filter(Q(asset__asset_tag__icontains=q) | Q(asset__device_name__icontains=q)
                           | Q(employee__name__icontains=q) | Q(employee__employee_code__icontains=q))
        rows, meta = paginate(request, qs, lambda a: self._row(a, exits))
        extra = {"summary": self._summary([self._row(a, exits) for a in self._pending(exits)])} if scope == "pending" else {}
        return ok("ASSET_RETURN_LIST", "Asset returns fetched.", rows, meta=meta, **extra)

    def retrieve(self, request, pk=None):
        a = (AssetAllocation.objects.filter(company=self.company(), is_active=True, pk=pk)
             .select_related("asset", "employee", "employee__department").first())
        if a is None:
            return err("NOT_FOUND", "Allocation not found.", 404)
        return ok("ASSET_RETURN_DETAIL", "Detail fetched.", self._row(a, self._exits()))

    @action(detail=False, methods=["get"], url_path="by-employee")
    def by_employee(self, request):
        exits = self._exits()
        groups = {}
        for a in self._pending(exits).order_by("employee__name", "id"):
            r = self._row(a, exits)
            g = groups.setdefault(a.employee_id, {"employee": r["employee"], "exit": r["exit"], "assets": []})
            g["assets"].append(r)
        out = []
        for g in groups.values():
            dues = [x["return_due_date"] for x in g["assets"] if x["return_due_date"]]
            out.append({**g, "pending_count": len(g["assets"]), "earliest_due": min(dues) if dues else None,
                        "overdue": any(x["overdue"] for x in g["assets"])})
        flat = [r for g in out for r in g["assets"]]
        return ok("ASSET_RETURN_BY_EMPLOYEE", "Pending returns by employee.", out, summary=self._summary(flat))

    # ---- write ----
    @action(detail=False, methods=["post"], url_path="request")
    @transaction.atomic
    def request_return(self, request):
        """Flag asset(s) for return (e.g. when HR starts offboarding). Idempotent: already-pending rows are skipped."""
        d = request.data
        try:
            if d.get("allocation_id"):
                targets = list(self._open().filter(pk=d["allocation_id"]))
            else:
                emp = emp_by_code(self.company(), d.get("employee_code"))
                targets = list(self._open().filter(employee=emp))
            due = to_date(d.get("due_date"))
        except ValueError as e:
            return err("VALIDATION", str(e))
        if not targets:
            return err("NOT_FOUND", "No allocated asset found for this request.", 404)
        exits, new, skipped = self._exits(), [], []
        for a in targets:
            if a.return_pending:
                skipped.append(a.id)
                continue
            a.return_pending, a.return_requested_on = True, timezone.localdate()
            a.return_due_date = due or (exits[a.employee_id].last_working_day if a.employee_id in exits else None)
            a.return_reason = (d.get("reason") or ("Offboarding - exit clearance" if a.employee_id in exits
                                                   else "Return requested by HR"))[:250]
            a.updated_by = self.actor()
            a.save()
            new.append(a)
        if not new:
            return err("ALREADY_PENDING", "Return is already requested for these assets.", 409,
                       errors={"already_pending": skipped})
        return ok("ASSET_RETURN_REQUESTED", f"Return requested for {len(new)} asset(s).",
                  {"requested": [self._row(a, exits) for a in new], "already_pending": skipped}, 201)

    def _clear_exit_item(self, emp):
        """Mark the 'IT' exit-clearance item cleared once the employee has no open allocation left."""
        x = active_exit(emp)
        if x is None or self._open().filter(employee=emp).exists():
            return False
        hit = False
        for i in x.items or []:
            if i.get("department") == "IT" and not i.get("cleared"):
                i.update(cleared=True, cleared_by=self.actor(), cleared_at=timezone.now().isoformat())
                hit = True
        if hit:
            x.status, x.updated_by = ("Cleared" if all(i.get("cleared") for i in x.items) else "In Progress"), self.actor()
            x.save()
        return hit

    @action(detail=True, methods=["post"])
    @transaction.atomic
    def receive(self, request, pk=None):
        """Mark one asset as physically received back (the 'recovery')."""
        a = self._find(pk)
        if a is None:
            return err("NOT_FOUND", "Open allocation not found (already returned?).", 404)
        d = request.data
        emp = a.employee
        try:
            do_close(a, d, self.actor(), return_asset_status(d))
        except ValueError as e:
            transaction.set_rollback(True)
            return err("VALIDATION", str(e))
        cleared = self._clear_exit_item(emp) if to_bool(d.get("clear_exit_item")) else False
        return ok("ASSET_RETURN_RECEIVED", "Asset received back.",
                  {"return": self._row(a, {}), "asset_status": a.asset.status,
                   "remaining_for_employee": self._open().filter(employee=emp).count(), "exit_item_cleared": cleared})

    @action(detail=False, methods=["post"], url_path="receive-all")
    @transaction.atomic
    def receive_all(self, request):
        """Receive every asset an employee still holds (one click at the exit desk)."""
        d = request.data
        try:
            emp = emp_by_code(self.company(), d.get("employee_code"))
        except ValueError as e:
            return err("VALIDATION", str(e))
        rows = list(self._open().filter(employee=emp))
        if not rows:
            return err("NOT_FOUND", "This employee holds no allocated assets.", 404)
        try:
            status = return_asset_status(d)
            for a in rows:
                do_close(a, d, self.actor(), status)
        except ValueError as e:
            transaction.set_rollback(True)
            return err("VALIDATION", str(e))
        cleared = self._clear_exit_item(emp) if to_bool(d.get("clear_exit_item")) else False
        return ok("ASSET_RETURN_RECEIVED_ALL", f"{len(rows)} asset(s) received back.",
                  {"employee": emp_brief(emp), "received": [self._row(a, {}) for a in rows], "exit_item_cleared": cleared})

    @action(detail=True, methods=["post"])
    def cancel(self, request, pk=None):
        """Withdraw an HR return request. (Employees in an exit process stay pending via the exit clearance.)"""
        a = self._find(pk)
        if a is None:
            return err("NOT_FOUND", "Open allocation not found.", 404)
        if not a.return_pending:
            return err("NOT_PENDING", "No HR return request to cancel on this allocation.", 409)
        a.return_pending, a.return_requested_on, a.return_due_date, a.return_reason = False, None, None, None
        a.updated_by = self.actor()
        a.save()
        row = self._row(a, self._exits())
        return ok("ASSET_RETURN_CANCELLED", "Return request cancelled.", row,
                  still_pending_due_to_exit=row["source"] == "EXIT_CLEARANCE")


# ============================================================
# ASSET HISTORY tab - "Hardware Maintenance & Lifecycle Log"
#   /api/people/asset-history/        CRUD on AssetMaintenance rows (repair, battery, warranty ...)
#   /api/people/asset-history/lifecycle/   merged timeline (allocations + returns + audits + maintenance)
# ============================================================
class AssetMaintenanceViewSet(CrudBase):
    """
    GET  /api/people/asset-history/        ?asset=<tag|id> &event_type= &status= &from=YYYY-MM-DD &to= &search=
    POST /api/people/asset-history/        {asset_tag|asset_id, event_type, event_date?, vendor?, cost?, description?,
                                            warranty_until?, next_service_due?, status?}
    GET/PATCH/DELETE /<id>/   (also POST <id>/update/ and <id>/delete/)
    GET  /api/people/asset-history/summary/
    GET  /api/people/asset-history/lifecycle/   ?asset=<tag|id> &limit=
    """
    model = AssetMaintenance
    code = "ASSET_HISTORY"
    select = ("asset",)
    search_fields = ("asset__asset_tag", "asset__device_name", "vendor", "description")

    def build(self, m):
        return {"id": m.id, "asset_id": m.asset_id, "asset_tag": m.asset.asset_tag, "device_name": m.asset.device_name,
                "category": m.asset.category, "event_type": m.event_type, "event_date": iso(m.event_date),
                "vendor": m.vendor, "cost": float(m.cost) if m.cost is not None else None,
                "description": m.description, "warranty_until": iso(m.warranty_until),
                "next_service_due": iso(m.next_service_due), "status": m.status, "created_by": m.created_by,
                "created_at": m.created_at.isoformat() if m.created_at else None}

    def filter(self, qs, p):
        qs = super().filter(qs, {k: v for k, v in p.items() if k != "employee"})   # no employee column on this model
        if p.get("asset"):
            a = find_asset(self.company(), p["asset"])
            qs = qs.filter(asset=a) if a else qs.none()
        if p.get("event_type"):
            qs = qs.filter(event_type=p["event_type"])
        if p.get("from"):
            qs = qs.filter(event_date__gte=to_date(p["from"]))
        if p.get("to"):
            qs = qs.filter(event_date__lte=to_date(p["to"]))
        return qs

    def list(self, request):
        try:
            return super().list(request)
        except ValueError as e:
            return err("VALIDATION", str(e))

    def apply(self, m, d, creating):
        company = self.company()
        if creating:
            ref = d.get("asset_id") or d.get("asset_tag")
            asset = find_asset(company, ref)
            if asset is None:
                raise ValueError("Asset not found (send asset_tag or asset_id).")
            m.asset = asset
        elif any(k in d for k in ("asset_id", "asset_tag")):
            raise ValueError("An existing log entry cannot be moved to another asset.")
        if "event_type" in d:
            if d["event_type"] not in dict(AssetMaintenance.EVENT):
                raise ValueError(f"Invalid event_type. Allowed: {', '.join(dict(AssetMaintenance.EVENT))}")
            m.event_type = d["event_type"]
        if "status" in d:
            if d["status"] not in dict(AssetMaintenance.STATUS):
                raise ValueError(f"Invalid status. Allowed: {', '.join(dict(AssetMaintenance.STATUS))}")
            m.status = d["status"]
        if "event_date" in d:
            m.event_date = to_date(d["event_date"]) or timezone.localdate()
        for k in ("vendor", "description"):
            if k in d:
                setattr(m, k, d[k])
        if "cost" in d:
            m.cost = to_decimal(d["cost"])
            if m.cost is not None and m.cost < 0:
                raise ValueError("cost cannot be negative.")
        for k in ("warranty_until", "next_service_due"):
            if k in d:
                setattr(m, k, to_date(d[k]))
        # duplicate guard: same asset + type + date + description is the same log entry
        dup = AssetMaintenance.objects.filter(company=company, is_active=True, asset=m.asset, event_type=m.event_type,
                                              event_date=m.event_date, description__iexact=m.description or "")
        if dup.exclude(pk=m.pk).exists():
            raise ValueError("Duplicate entry: this maintenance event is already logged for the asset.")

    def after_save(self, m, creating):
        """Keep the asset master in sync (warranty date + Under Repair state). Never touches an allocated asset."""
        a, changed = m.asset, False
        if m.warranty_until and (a.warranty_until is None or m.warranty_until > a.warranty_until):
            a.warranty_until, changed = m.warranty_until, True
        if a.status in ("Available", "Under Repair") and m.event_type == "Repair":
            if m.status == "In Progress" and a.status == "Available":
                a.status, changed = "Under Repair", True
            elif m.status == "Completed" and a.status == "Under Repair" and not a.maintenance_logs.filter(
                    is_active=True, event_type="Repair", status="In Progress").exclude(pk=m.pk).exists():
                a.status, changed = "Available", True
        if changed:
            a.updated_by = self.actor()
            a.save()

    @action(detail=False, methods=["get"])
    def summary(self, request):
        c, today = self.company(), timezone.localdate()
        qs = self.scope().filter(is_active=True)
        by_type = {k: qs.filter(event_type=k).count() for k, _ in AssetMaintenance.EVENT}
        due = {}
        for m in qs.filter(next_service_due__gte=today, next_service_due__lte=today + timedelta(days=30)
                           ).order_by("next_service_due"):
            due.setdefault(m.asset_id, {"asset_tag": m.asset.asset_tag, "device_name": m.asset.device_name,
                                        "next_service_due": iso(m.next_service_due)})
        assets = AssetMaster.objects.filter(company=c, is_active=True)
        return ok("ASSET_HISTORY_SUMMARY", "Maintenance summary.", {
            "total_entries": qs.count(), "by_event_type": {k: v for k, v in by_type.items() if v},
            "in_progress": qs.filter(status="In Progress").count(),
            "total_cost": float(qs.aggregate(t=Sum("cost"))["t"] or 0),
            "service_due_30d": list(due.values()),
            "warranty_expiring_60d": [{"asset_tag": a.asset_tag, "device_name": a.device_name,
                                       "warranty_until": iso(a.warranty_until)} for a in assets.filter(
                warranty_until__gte=today, warranty_until__lte=today + timedelta(days=60)).order_by("warranty_until")]})

    @action(detail=False, methods=["get"])
    def lifecycle(self, request):
        p = request.query_params
        asset = None
        if p.get("asset"):
            asset = find_asset(self.company(), p["asset"])
            if asset is None:
                return err("NOT_FOUND", "Asset not found.", 404)
        try:
            limit = max(1, min(int(p.get("limit", 100)), 500))
        except ValueError:
            limit = 100
        return ok("ASSET_LIFECYCLE", "Lifecycle log.", lifecycle_events(self.company(), asset, limit))
        
        

# ============================================================
# ADDITIVE PATCH (security): asset admin APIs are NOT for ordinary employees.
# EmployeeRole.can_view_employees defaults to True, so every basic employee could READ the whole
# company inventory (serials, costs, custodians, CSV export).  Company Admin is unchanged; an employee
# role now needs at least one write-type Employees checkbox (create / edit / delete / manage) - i.e. HR/IT.
# Employees use /employee/assets/ (People/views_employee_assets.py) for their OWN assets.
# ============================================================
from .common import IsPeopleUser as _IsPeopleUser, people_allows as _people_allows   # noqa: E402
from Employee.employee_crud_permissions import resolve_actor_role as _actor_role      # noqa: E402


class IsAssetStaff(_IsPeopleUser):
    message = "Asset management is restricted to Admin / HR / IT roles. Use /employee/assets/ for your own assets."

    def has_permission(self, request, view):
        if not super().has_permission(request, view):
            return False
        if _actor_role(request.user) == "admin":
            return True
        return any(_people_allows(request.user, a) for a in ("create", "edit", "delete"))


for _vs in (AssetMasterViewSet, AllocationViewSet, AssetReturnViewSet, AssetMaintenanceViewSet):
    _vs.permission_classes = [IsAssetStaff]

