# ============================================================
# ADDITIVE: Time, Biometrics & Perimeter Security (Attendance Hub) - models
# ------------------------------------------------------------
# DUPLICATE CHECK - every existing model was reviewed first:
#   Employee.EMP_check_in_check_out  REUSED - the punch record (login/logout, GPS, photo). Every
#                                    path (web, mobile, biometric, field, regularization) writes here.
#   Employee.AttendanceEmp           REUSED - day status, written by the existing scheduler; the
#                                    regularization apply only upserts it for PAST days.
#   Employee.leave_models.WFHPolicy / WFHRequest   REUSED - approved WFH today, weekly quota.
#   Company.company_details          REUSED - office_latitude / office_longitude / allowed_radius are the
#                                    default perimeter until a geofence is saved.
#   People.Branch                    REUSED - geofence / device location.
#   AdminCenter.IntegrationConnector REUSED - the central biometric gateway URL (type "Biometric") and its
#                                    SSRF-guarded ping (AdminCenter.services.ping_endpoint).
#   Company.Attendance_Status        auto-absent job marker - untouched.
#   Existing roles                   can_*_attendance checkboxes are used for permissions.
#
# New (nothing equivalent existed):
#   AttendancePolicy         shift start/end, grace, perimeter / WFH-redirect switches, ping interval
#   AttendanceGeofence       office perimeters (lat/long/radius + whitelisted Wi-Fi/IP ranges)
#   BiometricDevice          eSSL / ZKTeco / Matrix / Suprema terminals (+ device API key)
#   BiometricEnrollment      employee <-> biometric / card id
#   BiometricPunch           raw ingestion buffer + reconcile status
#   AttendancePunchMeta      how a check-in happened (source, device, perimeter verdict) - 1:1 side table
#   PerimeterEvent           blocked / redirected punch attempts (security audit log)
#   FieldForceAgent          field employees (territory, ping interval, per-km rate)
#   FieldTrackPoint          30-minute pings, client check-ins, route breadcrumbs
#   AttendanceRegularization REG-001 requests and their approval
#   EsslSource               connection to the eSSL (eTimeTrack) database that holds the raw device logs
#                            (MySQL -> HRMS MySQL sync) + the read cursor
#   EsslSyncRun              one row per sync / PDF import (what was read, reconciled, unmatched)
#
# Imported at the bottom of People/models.py (one additive line).
# ============================================================
from datetime import time
from decimal import Decimal

from django.db import models
from django.db.models import Q

from Company.models import company_details
from Employee.models import EMP_check_in_check_out, EmployeeDT

from .models import Audit, Branch

__all__ = ["AttendancePolicy", "AttendanceGeofence", "BiometricDevice", "BiometricEnrollment", "BiometricPunch",
           "AttendancePunchMeta", "PerimeterEvent", "FieldForceAgent", "FieldTrackPoint", "AttendanceRegularization",
           "EsslSource", "EsslSyncRun"]


class AttendancePolicy(Audit):
    company = models.OneToOneField(company_details, on_delete=models.CASCADE, related_name="people_attendance_policy")
    shift_start = models.TimeField(default=time(9, 0))
    shift_end = models.TimeField(default=time(18, 0))
    grace_minutes = models.PositiveSmallIntegerField(default=15)               # late arrival grace
    early_leave_grace_minutes = models.PositiveSmallIntegerField(default=15)   # early departure grace
    perimeter_enforced = models.BooleanField(default=True)
    allow_web_punch = models.BooleanField(default=True)
    allow_mobile_punch = models.BooleanField(default=True)
    wfh_redirect_enabled = models.BooleanField(default=True)
    field_ping_interval_minutes = models.PositiveSmallIntegerField(default=30)
    device_online_minutes = models.PositiveSmallIntegerField(default=10)       # no heartbeat for this long = Offline
    ingestion_mode = models.CharField(max_length=80, default="Direct TCP/IP Polling (Zero Buffer Loss)")
    reconcile_interval_seconds = models.PositiveIntegerField(default=60)


class AttendanceGeofence(Audit):
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_geofences")
    name = models.CharField(max_length=150)                                    # Pune Tech HQ & R&D Campus
    branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True, blank=True, related_name="geofences")
    latitude = models.FloatField()
    longitude = models.FloatField()
    radius_m = models.PositiveIntegerField(default=200)
    ip_ranges = models.JSONField(default=list, blank=True)                     # ["192.168.1.0/24"] Office Wi-Fi subnets
    is_primary = models.BooleanField(default=False)
    notes = models.TextField(blank=True, null=True)

    class Meta:
        ordering = ["-is_primary", "name"]
        unique_together = (("company", "name"),)


class BiometricDevice(Audit):
    VENDORS = [("eSSL", "eSSL"), ("ZKTeco", "ZKTeco"), ("Matrix", "Matrix"), ("Suprema", "Suprema"), ("Other", "Other")]
    PROTOCOLS = [("Push API / TCP-IP", "Push API / TCP-IP"), ("SQL Mirror / WebSocket", "SQL Mirror / WebSocket"),
                 ("REST API Endpoint", "REST API Endpoint"), ("Direct TCP Socket", "Direct TCP Socket")]
    STATUS = [("Enabled", "Enabled"), ("Disabled", "Disabled"), ("Maintenance", "Maintenance")]

    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_bio_devices")
    device_code = models.CharField(max_length=30)                              # BIO-DEV-01
    name = models.CharField(max_length=150)                                    # eSSL SilkBio-101TC
    vendor = models.CharField(max_length=10, choices=VENDORS, default="Other")
    location_label = models.CharField(max_length=200, blank=True, null=True)   # Pune Tech HQ - Main Reception Turnstile
    branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True, blank=True, related_name="bio_devices")
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    port = models.PositiveIntegerField(null=True, blank=True)
    sync_protocol = models.CharField(max_length=24, choices=PROTOCOLS, default="Push API / TCP-IP")
    firmware = models.CharField(max_length=60, blank=True, null=True)
    status = models.CharField(max_length=12, choices=STATUS, default="Enabled", db_index=True)
    api_key_hash = models.CharField(max_length=64, blank=True, null=True, db_index=True)   # sha256 - the key itself is never stored
    api_key_hint = models.CharField(max_length=12, blank=True, null=True)
    last_seen_at = models.DateTimeField(null=True, blank=True)
    last_sync_at = models.DateTimeField(null=True, blank=True)
    last_ping_ok = models.BooleanField(null=True, blank=True)
    last_ping_ms = models.PositiveIntegerField(null=True, blank=True)
    last_ping_message = models.CharField(max_length=300, blank=True, null=True)

    class Meta:
        ordering = ["device_code"]
        unique_together = (("company", "device_code"),)


class BiometricEnrollment(Audit):
    MODES = [("Fingerprint", "Fingerprint"), ("Face Recognition", "Face Recognition"),
             ("Smart Card + PIN", "Smart Card + PIN"), ("Iris", "Iris"), ("Other", "Other")]

    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_bio_enrollments")
    employee = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="bio_enrollments")
    biometric_id = models.CharField(max_length=60)                             # FP-0248 / FACE-0504 / RFID-0311
    verification_mode = models.CharField(max_length=20, choices=MODES, default="Fingerprint")
    notes = models.TextField(blank=True, null=True)

    class Meta:
        ordering = ["biometric_id"]
        unique_together = (("company", "biometric_id"),)


class BiometricPunch(Audit):
    DIRECTIONS = [("IN", "IN"), ("OUT", "OUT")]
    SYNC = [("Reconciled", "Reconciled"), ("Pending", "Pending"), ("Unmatched", "Unmatched"),
            ("Duplicate", "Duplicate"), ("Failed", "Failed")]

    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_bio_punches")
    device = models.ForeignKey(BiometricDevice, on_delete=models.SET_NULL, null=True, blank=True, related_name="punches")
    device_code = models.CharField(max_length=30, blank=True, null=True)       # snapshot
    biometric_id = models.CharField(max_length=60)
    employee = models.ForeignKey(EmployeeDT, on_delete=models.SET_NULL, null=True, blank=True, related_name="bio_punches")
    punch_time = models.DateTimeField(db_index=True)
    direction = models.CharField(max_length=3, choices=DIRECTIONS, default="IN")
    verification_mode = models.CharField(max_length=40, blank=True, null=True)
    match_score = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    sync_status = models.CharField(max_length=10, choices=SYNC, default="Pending", db_index=True)
    sync_message = models.CharField(max_length=300, blank=True, null=True)
    checkin = models.ForeignKey(EMP_check_in_check_out, on_delete=models.SET_NULL, null=True, blank=True, related_name="bio_punches")
    raw_payload = models.JSONField(default=dict, blank=True)
    source = models.CharField(max_length=10, default="device")                 # device | manual

    class Meta:
        ordering = ["-punch_time", "-id"]
        constraints = [models.UniqueConstraint(fields=["company", "device_code", "biometric_id", "punch_time", "direction"],
                                               name="uniq_people_bio_punch")]


class AttendancePunchMeta(Audit):
    SOURCES = [("Biometric Device", "Biometric Device"), ("GPS Mobile Punch", "GPS Mobile Punch"),
               ("Web Portal Punch", "Web Portal Punch"), ("Field Tracker", "Field Tracker"),
               ("Regularization", "Regularization"), ("Manual", "Manual")]
    VERDICTS = [("In-Perimeter Verified", "In-Perimeter Verified"), ("Authorized WFH", "Authorized WFH"),
                ("Field Force", "Field Force"), ("Device Verified", "Device Verified"),
                ("Regularized", "Regularized"), ("Manual Entry", "Manual Entry"), ("Unverified", "Unverified")]

    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_punch_meta")
    checkin = models.OneToOneField(EMP_check_in_check_out, on_delete=models.CASCADE, related_name="punch_meta")
    source = models.CharField(max_length=20, choices=SOURCES)
    perimeter_status = models.CharField(max_length=24, choices=VERDICTS, default="Unverified")
    device = models.ForeignKey(BiometricDevice, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    geofence = models.ForeignKey(AttendanceGeofence, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    distance_m = models.DecimalField(max_digits=10, decimal_places=1, null=True, blank=True)
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    checkout_source = models.CharField(max_length=20, blank=True, null=True)
    regularization_id = models.PositiveIntegerField(null=True, blank=True)


class PerimeterEvent(Audit):
    STATUS = [("Blocked by Perimeter Lock", "Blocked by Perimeter Lock"), ("Redirected to WFH Portal", "Redirected to WFH Portal"),
              ("Overridden by HR", "Overridden by HR"), ("Resolved", "Resolved")]

    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_perimeter_events")
    employee = models.ForeignKey(EmployeeDT, on_delete=models.SET_NULL, null=True, blank=True, related_name="perimeter_events")
    employee_code = models.CharField(max_length=100, blank=True, null=True)
    event_time = models.DateTimeField(db_index=True)
    attempted_action = models.CharField(max_length=60)                         # Web Check-in Punch / Mobile Web Punch
    detected_ip = models.GenericIPAddressField(null=True, blank=True)
    latitude = models.FloatField(null=True, blank=True)
    longitude = models.FloatField(null=True, blank=True)
    distance_m = models.DecimalField(max_digits=10, decimal_places=1, null=True, blank=True)
    geofence = models.ForeignKey(AttendanceGeofence, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    breach_reason = models.TextField(blank=True, null=True)
    status = models.CharField(max_length=26, choices=STATUS, default="Blocked by Perimeter Lock", db_index=True)
    resolved_by = models.CharField(max_length=150, blank=True, null=True)
    resolved_at = models.DateTimeField(null=True, blank=True)
    resolution_note = models.TextField(blank=True, null=True)

    class Meta:
        ordering = ["-event_time", "-id"]


class FieldForceAgent(Audit):
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_field_agents")
    employee = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="field_agent_profiles")
    territory = models.CharField(max_length=150, blank=True, null=True)        # Mumbai Metropolitan Region (MMR)
    ping_interval_minutes = models.PositiveSmallIntegerField(default=30)
    per_km_rate = models.DecimalField(max_digits=8, decimal_places=2, default=Decimal("0"))   # travel claim rate

    class Meta:
        unique_together = (("company", "employee"),)


class FieldTrackPoint(Audit):
    TYPES = [("Punch-In", "Punch-In"), ("Interval Ping", "Interval Ping"), ("Client Check-In", "Client Check-In"),
             ("Punch-Out", "Punch-Out")]

    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_field_points")
    agent = models.ForeignKey(FieldForceAgent, on_delete=models.CASCADE, related_name="points")
    recorded_at = models.DateTimeField(db_index=True)
    point_type = models.CharField(max_length=16, choices=TYPES, default="Interval Ping")
    location_label = models.CharField(max_length=200, blank=True, null=True)
    client_name = models.CharField(max_length=200, blank=True, null=True)
    latitude = models.FloatField()
    longitude = models.FloatField()
    speed_kmh = models.DecimalField(max_digits=6, decimal_places=1, null=True, blank=True)
    battery_percent = models.PositiveSmallIntegerField(null=True, blank=True)
    notes = models.CharField(max_length=300, blank=True, null=True)
    site_verified = models.BooleanField(default=False)                         # geofence confirmed at client site

    class Meta:
        ordering = ["recorded_at", "id"]


class AttendanceRegularization(Audit):
    STATUS = [("Pending Approval", "Pending Approval"), ("Approved", "Approved"), ("Rejected", "Rejected"),
              ("Cancelled", "Cancelled")]

    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_regularizations")
    request_id = models.CharField(max_length=30)                               # REG-001
    employee = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="regularizations")
    attendance_date = models.DateField(db_index=True)
    punch_in_time = models.TimeField()
    punch_out_time = models.TimeField(null=True, blank=True)
    reason = models.TextField()
    status = models.CharField(max_length=16, choices=STATUS, default="Pending Approval", db_index=True)
    requested_by = models.CharField(max_length=10, default="HR")               # HR | Employee
    reviewed_by = models.CharField(max_length=150, blank=True, null=True)
    reviewed_at = models.DateTimeField(null=True, blank=True)
    review_comment = models.TextField(blank=True, null=True)
    applied_checkin = models.ForeignKey(EMP_check_in_check_out, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")

    class Meta:
        ordering = ["-attendance_date", "-id"]
        constraints = [
            models.UniqueConstraint(fields=["company", "request_id"], name="uniq_people_reg_request_id"),
            models.UniqueConstraint(fields=["company", "employee", "attendance_date"],
                                    condition=Q(status__in=["Pending Approval", "Approved"]), name="uniq_people_reg_open"),
        ]


class EsslSource(Audit):
    """Read-only connection to the eSSL software database (table DeviceLogs_<month>_<year>)."""

    TYPES = [("mysql", "MySQL"), ("sqlite", "SQLite (dev / test only)")]
    STATUS = [("Idle", "Idle"), ("Running", "Running"), ("Success", "Success"), ("Error", "Error")]

    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_essl_sources")
    name = models.CharField(max_length=120)
    source_type = models.CharField(max_length=10, choices=TYPES, default="mysql")
    host = models.CharField(max_length=255)                      # sqlite: file path
    port = models.PositiveIntegerField(default=3306)
    database = models.CharField(max_length=120, blank=True, null=True)
    username = models.CharField(max_length=120, blank=True, null=True)
    password_enc = models.TextField(blank=True, null=True)       # Fernet token (AdminCenter.common.encrypt_secret) - never returned
    table_pattern = models.CharField(max_length=120, default="DeviceLogs_{month}_{year}")
    id_column = models.CharField(max_length=64, default="DeviceLogId")
    user_column = models.CharField(max_length=64, default="UserId")
    time_column = models.CharField(max_length=64, default="LogDate")
    device_column = models.CharField(max_length=64, blank=True, null=True, default="DeviceId")
    direction_column = models.CharField(max_length=64, blank=True, null=True, default="Direction")
    device_map = models.JSONField(default=dict, blank=True)      # {"1": "BIO-DEV-01"}
    start_from_date = models.DateField(null=True, blank=True)    # ignore log rows older than this
    batch_size = models.PositiveIntegerField(default=500)
    poll_interval_seconds = models.PositiveIntegerField(default=60)
    min_gap_minutes = models.PositiveSmallIntegerField(default=2)  # a second scan inside this gap is a double scan
    auto_enroll = models.BooleanField(default=False)             # UserId equal to an employee_code -> enroll automatically
    enabled = models.BooleanField(default=True)
    cursor = models.JSONField(default=dict, blank=True)          # {"2026_9": 1234}  last DeviceLogId per monthly table
    last_status = models.CharField(max_length=10, choices=STATUS, default="Idle")
    running_since = models.DateTimeField(null=True, blank=True)
    last_sync_at = models.DateTimeField(null=True, blank=True)
    last_error = models.TextField(blank=True, null=True)
    total_rows_synced = models.PositiveBigIntegerField(default=0)

    class Meta:
        ordering = ["name"]
        unique_together = (("company", "name"),)


class EsslSyncRun(Audit):
    KINDS = [("live", "Live sync"), ("manual", "Manual sync"), ("pdf-import", "PDF import")]
    STATUS = [("Running", "Running"), ("Success", "Success"), ("Partial", "Partial"), ("Error", "Error")]

    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_essl_runs")
    source = models.ForeignKey(EsslSource, on_delete=models.SET_NULL, null=True, blank=True, related_name="runs")
    kind = models.CharField(max_length=12, choices=KINDS, default="live")
    trigger = models.CharField(max_length=20, default="command")                # command | api | import
    status = models.CharField(max_length=8, choices=STATUS, default="Running", db_index=True)
    started_at = models.DateTimeField(auto_now_add=True)
    finished_at = models.DateTimeField(null=True, blank=True)
    rows_fetched = models.PositiveIntegerField(default=0)
    accepted = models.PositiveIntegerField(default=0)
    reconciled = models.PositiveIntegerField(default=0)
    unmatched = models.PositiveIntegerField(default=0)
    duplicates = models.PositiveIntegerField(default=0)
    failed = models.PositiveIntegerField(default=0)
    file_name = models.CharField(max_length=200, blank=True, null=True)
    error = models.TextField(blank=True, null=True)
    detail = models.JSONField(default=dict, blank=True)

    class Meta:
        ordering = ["-id"]
