# ============================================================
# ADDITIVE: direct device connection + .xls report import - Admin / HR API
# Mounted via People/essl_direct_urls.py  ->  /api/attendance-hub/...
#   GET|PUT|PATCH devices/<id>/connection/   {zk_port?, comm_key?, pull_enabled?, direction_mode?, min_gap_minutes?, auto_enroll?, pull_since?}
#                                            comm_key is write-only (stored encrypted, never returned)
#   POST devices/<id>/connection/test/       connect to the terminal and read its serial number / clock
#   POST devices/<id>/pull/                  pull the new punches of this device now
#   POST devices/pull-all/                   every enabled device with pull_enabled
#   POST essl/import/xls/                    multipart, same fields as essl/import/pdf/ (file = the .xls report)
# Permissions: attendance VIEW to read, attendance MANAGE to change / pull / import.
# ============================================================
import json

from django.db import transaction
from rest_framework.parsers import FormParser, JSONParser, MultiPartParser

from . import essl_direct as ed
from . import essl_sync as es
from . import essl_xls
from .att_models import BiometricDevice
from .common import err, iso, ok, to_bool, to_date, to_int
from .essl_pdf import PdfFormatError, summarize
from .essl_direct_models import BiometricDeviceLink
from .views_att import AttView
from .views_att_essl import IsAttendanceManager, run_row

MAX_XLS_BYTES = 25 * 1024 * 1024


class ManageView(AttView):
    permission_classes = [IsAttendanceManager]
    permission_action_map = {}

    def device(self, pk):
        return BiometricDevice.objects.filter(company=self.company(), pk=pk, is_active=True).first()


def link_row(link):
    return {"device_id": link.device_id, "device_code": link.device.device_code, "ip_address": link.device.ip_address,
            "zk_port": link.zk_port, "comm_key_set": bool(link.comm_key_enc), "pull_enabled": link.pull_enabled,
            "direction_mode": link.direction_mode, "min_gap_minutes": link.min_gap_minutes, "auto_enroll": link.auto_enroll,
            "pull_since": iso(link.pull_since), "cursor_time": iso(link.cursor_time), "serial_number": link.serial_number,
            "device_name": link.device_name, "last_status": link.last_status, "last_pull_at": iso(link.last_pull_at),
            "last_error": link.last_error, "total_pulled": link.total_pulled}


class DeviceConnectionView(ManageView):
    def get(self, request, pk):
        d = self.device(pk)
        if d is None:
            return err("NOT_FOUND", "Device not found.", 404)
        return ok("DEVICE_LINK", "Device connection.", link_row(ed.get_link(d, self.actor())))

    def patch(self, request, pk):
        d = self.device(pk)
        if d is None:
            return err("NOT_FOUND", "Device not found.", 404)
        link, data = ed.get_link(d, self.actor()), request.data
        try:
            if "zk_port" in data:
                p = to_int(data["zk_port"])
                if p is None or not (1 <= p <= 65535):
                    raise ValueError("zk_port must be between 1 and 65535.")
                link.zk_port = p
            if "comm_key" in data:
                if data["comm_key"] not in (None, "") and not str(data["comm_key"]).isdigit():
                    raise ValueError("comm_key must be a number (0 = no key).")
                ed.set_comm_key(link, data["comm_key"])
            if "direction_mode" in data:
                if data["direction_mode"] not in dict(BiometricDeviceLink.DIRECTION_MODES):
                    raise ValueError("direction_mode must be auto or device.")
                link.direction_mode = data["direction_mode"]
            if "min_gap_minutes" in data:
                g = to_int(data["min_gap_minutes"])
                if g is None or not (0 <= g <= 60):
                    raise ValueError("min_gap_minutes must be between 0 and 60.")
                link.min_gap_minutes = g
            for f in ("pull_enabled", "auto_enroll"):
                if f in data:
                    setattr(link, f, to_bool(data[f]))
            if "pull_since" in data:
                link.pull_since = to_date(data["pull_since"])
        except ValueError as e:
            return err("VALIDATION", str(e))
        link.updated_by = self.actor()
        link.save()
        return ok("DEVICE_LINK_SAVED", "Device connection saved.", link_row(link))

    put = patch


class DeviceConnectionTestView(ManageView):
    def post(self, request, pk):
        d = self.device(pk)
        if d is None:
            return err("NOT_FOUND", "Device not found.", 404)
        link = ed.get_link(d, self.actor())
        try:
            info = ed.test_device(d, link)
        except Exception as e:
            return ok("DEVICE_LINK_TEST", "Connection failed.", {"connected": False, "message": str(e)[:300]})
        return ok("DEVICE_LINK_TEST", "Connected.", info)


class DevicePullView(ManageView):
    def post(self, request, pk):
        d = self.device(pk)
        if d is None:
            return err("NOT_FOUND", "Device not found.", 404)
        if d.status != "Enabled":
            return err("CONFLICT", f"The device is {d.status}.", 409)
        run = ed.pull_device(d, trigger="api")
        return ok("DEVICE_PULLED" if run.status != "Error" else "DEVICE_PULL_FAILED", f"Pull {run.status.lower()}.",
                  {"run": run_row(run), "device": link_row(ed.get_link(d))})


class DevicePullAllView(ManageView):
    def post(self, request):
        ids = BiometricDeviceLink.objects.filter(company=self.company(), pull_enabled=True, is_active=True).values_list("device_id", flat=True)
        devs = BiometricDevice.objects.filter(company=self.company(), pk__in=ids, is_active=True, status="Enabled")
        runs = [run_row(ed.pull_device(d, trigger="api")) for d in devs]
        return ok("DEVICES_PULLED", "All enabled devices pulled.", {"devices": len(runs), "runs": runs})


class EsslXlsImportView(ManageView):
    """POST essl/import/xls/  - exactly like essl/import/pdf/ but the file is the eSSL .xls report (Basic or Four-Punch)."""
    parser_classes = [MultiPartParser, FormParser, JSONParser]

    def post(self, request):
        f = request.FILES.get("file")
        if f is None:
            return err("VALIDATION", "Upload the .xls in the 'file' field (multipart/form-data).", errors={"file": ["This field is required."]})
        if f.size > MAX_XLS_BYTES:
            return err("VALIDATION", "The file is larger than 25 MB.")
        if f.read(8) != b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1":
            return err("VALIDATION", "The uploaded file is not an .xls (Excel 97-2003) file.")
        f.seek(0)
        d = request.data
        try:
            emap = d.get("employee_map") or {}
            if isinstance(emap, str):
                emap = json.loads(emap) if emap.strip() else {}
            if not isinstance(emap, dict):
                raise ValueError("employee_map must be an object.")
            codes = d.get("include_codes")
            codes = [c.strip() for c in codes.split(",") if c.strip()] if isinstance(codes, str) else (codes or None)
            parsed = essl_xls.parse_report(f)
            with transaction.atomic():
                result, run = es.import_report(
                    self.company(), parsed, file_name=f.name, dry_run=to_bool(d.get("dry_run", "true")), employee_map=emap,
                    save_enrollments=to_bool(d.get("save_enrollments")), auto_enroll=to_bool(d.get("auto_enroll")),
                    day_status=d.get("day_status") or "present_only", overwrite_day_status=to_bool(d.get("overwrite_day_status")),
                    include_codes=codes, actor=self.actor())
        except (ValueError, PdfFormatError, json.JSONDecodeError) as e:
            return err("VALIDATION", str(e))
        result["report"] = {**summarize(parsed), "company": parsed["company"], "printed_on": parsed["printed_on"], "file_name": f.name}
        result["run_id"] = run.id if run else None
        return ok("ESSL_XLS_PREVIEW" if result["dry_run"] else "ESSL_XLS_IMPORTED",
                  "Report parsed (nothing saved)." if result["dry_run"] else "Report imported.", result, 200 if result["dry_run"] else 201)
