# ============================================================
# ADDITIVE: Time, Biometrics & Perimeter Security - DEVICE-FACING API
# ------------------------------------------------------------
# Biometric terminals / gateways push punches here. They do NOT use JWT: every call carries the
# device API key (shown once when the device was created / rotated):
#     X-Device-Key: bdk_biodev01_xxxxxxxx
#   POST /api/attendance-hub/device/ingest/     {"punches": [{"biometric_id", "punch_time", "direction", "verification_mode", "match_score"}]}
#   POST /api/attendance-hub/device/heartbeat/  {"firmware": "v2.0-secure"}
# Idempotent: re-sending the same punch answers "already_received" and creates nothing twice.
# ============================================================
from datetime import timedelta

from django.db import transaction
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from rest_framework import authentication, exceptions
from rest_framework.permissions import BasePermission
from rest_framework.views import APIView

from . import att_engine as en
from .att_models import BiometricPunch
from .common import err, ok, to_decimal

MAX_BATCH = 500
MAX_AGE_DAYS = 30


class DevicePrincipal:
    is_authenticated = True

    def __init__(self, device):
        self.device = device
        self.company = device.company


class DeviceKeyAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        key = request.META.get("HTTP_X_DEVICE_KEY")
        if not key:
            return None
        dev = en.device_for_key(key)
        if dev is None:
            raise exceptions.AuthenticationFailed("Invalid device key.")
        return DevicePrincipal(dev), key

    def authenticate_header(self, request):
        return "X-Device-Key"


class IsDevice(BasePermission):
    def has_permission(self, request, view):
        return isinstance(request.user, DevicePrincipal)


class DeviceBase(APIView):
    authentication_classes = [DeviceKeyAuthentication]
    permission_classes = [IsDevice]


class DeviceHeartbeatView(DeviceBase):
    def post(self, request):
        dev = request.user.device
        if dev.status == "Disabled":
            return err("DEVICE_DISABLED", "This device is disabled.", 403)
        dev.last_seen_at = timezone.now()
        if request.data.get("firmware"):
            dev.firmware = str(request.data["firmware"])[:60]
        dev.save(update_fields=["last_seen_at", "firmware", "updated_at"])
        pol = en.get_policy(dev.company)
        return ok("DEVICE_HEARTBEAT", "Heartbeat received.", {
            "device_code": dev.device_code, "server_time": timezone.now().isoformat(), "reconcile_interval_seconds": pol.reconcile_interval_seconds,
            "status": dev.status})


class DeviceIngestView(DeviceBase):
    @transaction.atomic
    def post(self, request):
        dev = request.user.device
        if dev.status != "Enabled":
            return err("DEVICE_NOT_ENABLED", f"This device is {dev.status}.", 403)
        items = request.data.get("punches")
        if not isinstance(items, list) or not items:
            return err("VALIDATION", "punches must be a non-empty list.")
        if len(items) > MAX_BATCH:
            return err("VALIDATION", f"A batch can hold at most {MAX_BATCH} punches.")
        now = timezone.now()
        results, summary = [], {}
        for i, it in enumerate(items):
            res = {"index": i}
            try:
                if not isinstance(it, dict):
                    raise ValueError("Each punch must be an object.")
                bid = str(it.get("biometric_id") or "").strip()
                if not bid:
                    raise ValueError("biometric_id is required.")
                when = parse_datetime(str(it.get("punch_time") or ""))
                if when is None:
                    raise ValueError("punch_time must be an ISO date-time.")
                when = timezone.make_aware(when) if timezone.is_naive(when) else when
                if when > now + timedelta(minutes=5):
                    raise ValueError("punch_time is in the future.")
                if when < now - timedelta(days=MAX_AGE_DAYS):
                    raise ValueError(f"punch_time is older than {MAX_AGE_DAYS} days.")
                direction = str(it.get("direction") or "IN").upper()
                if direction not in ("IN", "OUT"):
                    raise ValueError("direction must be IN or OUT.")
                score = to_decimal(it.get("match_score"))
                if score is not None and not (0 <= score <= 100):
                    raise ValueError("match_score must be between 0 and 100.")
            except ValueError as e:
                res.update(status="rejected", message=str(e))
                summary["rejected"] = summary.get("rejected", 0) + 1
                results.append(res)
                continue
            existing = BiometricPunch.objects.filter(company=dev.company, device_code=dev.device_code, biometric_id=bid,
                                                     punch_time=when, direction=direction).first()
            if existing:
                res.update(status="already_received", sync_status=existing.sync_status, punch_id=existing.id)
                summary["already_received"] = summary.get("already_received", 0) + 1
                results.append(res)
                continue
            p = BiometricPunch.objects.create(company=dev.company, device=dev, device_code=dev.device_code, biometric_id=bid, punch_time=when,
                                              direction=direction, verification_mode=str(it.get("verification_mode") or "")[:40] or None,
                                              match_score=score, raw_payload=it, source="device", created_by=f"device:{dev.device_code}",
                                              updated_by=f"device:{dev.device_code}")
            en.reconcile(p, f"device:{dev.device_code}")
            res.update(status="accepted", sync_status=p.sync_status, sync_message=p.sync_message, punch_id=p.id,
                       employee_code=p.employee.employee_code if p.employee_id else None)
            summary[p.sync_status] = summary.get(p.sync_status, 0) + 1
            results.append(res)
        dev.last_seen_at = dev.last_sync_at = now
        dev.save(update_fields=["last_seen_at", "last_sync_at", "updated_at"])
        return ok("DEVICE_INGESTED", "Punches processed.", {"received": len(items), "summary": summary, "results": results})
