# ============================================================
# ADDITIVE: pull punches DIRECTLY from an eSSL / ZKTeco terminal (ZK protocol, TCP 4370) - needs `pip install pyzk`
# ------------------------------------------------------------
# Same safe path as the MySQL sync: every attendance log goes through essl_sync.ingest_punch(), so
#   * a punch is stored once (unique company+device+biometric_id+time+direction),
#   * it is reconciled into the EXISTING EMP_check_in_check_out records,
#   * running it again (or from two places) never creates duplicates.
# The device is only READ - logs are never cleared on the terminal.
#   python manage.py essl_pull --once | --loop --interval 30 --max-seconds 55 | --device-id 3
#   POST /api/attendance-hub/devices/<id>/pull/        POST /api/attendance-hub/devices/pull-all/
# NOTE: the server must reach the device IP (same LAN / VPN / port-forward). A cloud server cannot reach 192.168.x.x.
# ============================================================
from datetime import datetime, timedelta

from django.db import transaction
from django.utils import timezone

from AdminCenter.common import decrypt_secret, encrypt_secret

from . import essl_sync as es
from .att_models import EsslSyncRun
from .essl_direct_models import BiometricDeviceLink

STALE_RUN_MINUTES = 10
MAX_PER_PULL = 20000
VERIFY = {0: "Password", 1: "Fingerprint", 2: "Card", 3: "Password", 4: "Card", 15: "Face", 25: "Palm"}


def get_link(device, actor="system"):
    link = BiometricDeviceLink.objects.filter(device=device).first()
    if link is None:
        link = BiometricDeviceLink.objects.create(company=device.company, device=device, created_by=actor, updated_by=actor)
    return link


def set_comm_key(link, plain):
    link.comm_key_enc = encrypt_secret(str(plain)) if plain not in (None, "") else None


def _comm_key(link):
    raw = decrypt_secret(link.comm_key_enc) if link.comm_key_enc else "0"
    try:
        return int(raw)
    except ValueError:
        raise ValueError("The device Comm Key must be a number (0 = no key).")


def _zk(device, link):
    try:
        from zk import ZK
    except ImportError:
        raise ValueError("Install 'pyzk' on the server (pip install pyzk) to connect to the device directly.")
    if not device.ip_address:
        raise ValueError("The device has no IP address.")
    es.host_allowed(str(device.ip_address))
    return ZK(str(device.ip_address), port=int(link.zk_port or 4370), timeout=8, password=_comm_key(link), force_udp=False, ommit_ping=True)


def test_device(device, link):
    """Connect, read identity + clock. Never writes to the device."""
    conn = _zk(device, link).connect()
    try:
        info = {"connected": True, "serial_number": _safe(conn.get_serialnumber), "device_name": _safe(conn.get_device_name),
                "firmware": _safe(conn.get_firmware_version), "device_time": str(_safe(conn.get_time))}
    finally:
        _quiet(conn.disconnect)
    link.serial_number, link.device_name = info["serial_number"], info["device_name"]
    link.save(update_fields=["serial_number", "device_name", "updated_at"])
    return info


def _safe(fn):
    try:
        v = fn()
        return v if v is not None else None
    except Exception:
        return None


def _quiet(fn):
    try:
        fn()
    except Exception:
        pass


def _direction(rec, mode):
    if mode != "device":
        return None
    st = getattr(rec, "punch", None)
    if st in (0, 4):
        return "IN"
    if st in (1, 5):
        return "OUT"
    return None


def _claim(link):
    with transaction.atomic():
        l = BiometricDeviceLink.objects.select_for_update().get(pk=link.pk)
        if l.last_status == "Running" and l.running_since and timezone.now() - l.running_since < timedelta(minutes=STALE_RUN_MINUTES):
            return None
        l.last_status, l.running_since = "Running", timezone.now()
        l.save(update_fields=["last_status", "running_since"])
        return l


def pull_device(device, trigger="command"):
    """One pull of the new punches of one device. Returns the EsslSyncRun."""
    link = get_link(device)
    actor = f"essl-device:{device.device_code}"[:150]
    run = EsslSyncRun.objects.create(company=device.company, source=None, kind="live", trigger=trigger, created_by=actor, updated_by=actor,
                                     detail={"device_code": device.device_code, "mode": "direct"})
    link = _claim(link)
    stats = {"rows_fetched": 0, "accepted": 0, "reconciled": 0, "unmatched": 0, "duplicates": 0, "failed": 0}
    status, error, conn, unmatched_ids = "Success", None, None, []
    if link is None:
        run.status, run.finished_at, run.error = "Error", timezone.now(), "Another pull of this device is already running."
        run.save()
        return run
    try:
        if device.status != "Enabled":
            raise ValueError(f"The device is {device.status}.")
        conn = _zk(device, link).connect()
        logs = conn.get_attendance() or []
        now = timezone.now()
        rows = []
        for r in logs:
            ts = r.timestamp
            if not isinstance(ts, datetime):
                continue
            ts = timezone.make_aware(ts) if timezone.is_naive(ts) else ts
            if link.cursor_time and ts <= link.cursor_time:
                continue
            if link.pull_since and ts.date() < link.pull_since:
                continue
            if ts > now + timedelta(minutes=5):
                continue
            rows.append((ts, str(r.user_id).strip(), r))
        rows.sort(key=lambda x: (x[0], x[1]))
        newest = link.cursor_time
        for ts, uid, r in rows[:MAX_PER_PULL]:
            stats["rows_fetched"] += 1
            if not uid:
                continue
            p, created = es.ingest_punch(
                device.company, biometric_id=uid, when=ts, direction=_direction(r, link.direction_mode), device=device,
                device_code=device.device_code, verification=VERIFY.get(getattr(r, "status", None), "eSSL"),
                raw={"zk_uid": getattr(r, "uid", None), "zk_status": getattr(r, "status", None), "zk_punch": getattr(r, "punch", None)},
                source="device", actor=actor, min_gap=link.min_gap_minutes, auto_enroll=link.auto_enroll)
            if created:
                es._count(stats, p)
                if p.sync_status == "Unmatched" and uid not in unmatched_ids and len(unmatched_ids) < 20:
                    unmatched_ids.append(uid)
            newest = ts if newest is None or ts > newest else newest
        link.cursor_time = newest
        link.total_pulled += stats["rows_fetched"]
        if stats["failed"]:
            status = "Partial"
    except Exception as e:                                       # a dead device must never crash the poller
        status, error = "Error", str(e)[:1000]
    finally:
        if conn is not None:
            _quiet(conn.disconnect)
    now = timezone.now()
    link.last_status = "Error" if status == "Error" else "Success"
    link.last_error, link.running_since = error, None
    if status != "Error":
        link.last_pull_at = now
        device.last_seen_at = device.last_sync_at = now
        device.last_ping_ok = True
        device.save(update_fields=["last_seen_at", "last_sync_at", "last_ping_ok", "updated_at"])
    else:
        device.last_ping_ok, device.last_ping_message = False, (error or "")[:300]
        device.save(update_fields=["last_ping_ok", "last_ping_message", "updated_at"])
    link.save()
    for k, v in stats.items():
        setattr(run, k, v)
    run.status, run.finished_at, run.error = status, now, error
    run.detail = {"device_code": device.device_code, "mode": "direct", "unmatched_ids": unmatched_ids,
                  "cursor_time": link.cursor_time.isoformat() if link.cursor_time else None}
    run.save()
    return run
