File size: 59,980 Bytes
5a26b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
"""PyQt5 GUI: sidebar app with live monitor, employees + enrollment, attendance/reports, cameras, recognition models, settings."""
import logging, math, os, sys, tempfile, time
from datetime import date, datetime
from functools import lru_cache
import cv2
import numpy as np
from PyQt5.QtCore import QDate, QObject, QPointF, QRectF, QSize, Qt, QThread, QTime, QTimer, QUrl, pyqtSignal
from PyQt5.QtGui import QColor, QDesktopServices, QFont, QIcon, QImage, QPainter, QPainterPath, QPen, QPixmap, QPolygonF
from PyQt5.QtWidgets import (QApplication, QCheckBox, QComboBox, QDateEdit, QDialog, QDialogButtonBox, QDoubleSpinBox,
                             QFileDialog, QFormLayout, QFrame, QGridLayout, QGroupBox, QHBoxLayout, QLabel, QLayout, QLineEdit,
                             QListWidget, QListWidgetItem, QMainWindow, QMessageBox, QProgressBar, QPushButton, QScrollArea,
                             QAbstractSpinBox, QSizePolicy, QSpinBox, QStackedWidget, QTableWidget, QTableWidgetItem, QTabWidget, QTimeEdit,
                             QVBoxLayout, QWidget)
from core import (DAILY, MODELS, MONTHLY, RUNTIMES, Attendance, CameraManager, Collector, Database, Gallery, Tracker, daily_rows, ensure_model, export,
                  hash_password, imwrite, load_engine, mask_url, model_path, monthly_rows, probe, verify_password)

log = logging.getLogger("ams")
COLORS = {"known": (94, 197, 34), "unknown": (68, 68, 239), "pending": (11, 158, 245), "low_quality": (148, 163, 184)}  # BGR
TAGS = {"Present": "#16a34a", "Late": "#d97706", "Absent": "#dc2626", "Leave": "#7c3aed", "Holiday": "#0891b2", "Yes": "#16a34a",
        "No": "#94a3b8", "check_in": "#16a34a", "check_out": "#2563eb", "unknown": "#dc2626", "seen": "#64748b"}
STATUSES = ["Present", "Late", "Leave", "Absent", "Holiday"]
STREAM = {"online": "#22c55e", "connecting": "#f59e0b", "reconnecting": "#f59e0b", "stopped": "#64748b"}

THEME = """
* { font-family: "UIFONT"; font-size: 10.5pt; color: #0f172a; }
QMainWindow, QDialog, #page { background: #f1f5f9; }
#sidebar { background: #0f172a; }
#sidebar QLabel { color: #cbd5e1; }
#brand { font-size: 18pt; font-weight: 700; color: #ffffff; }
#brandSub { color: #64748b; font-size: 9pt; }
#nav, #events { background: transparent; border: none; outline: none; }
#nav::item { color: #cbd5e1; padding: 12px 14px; margin: 3px 0; border: none; border-radius: 10px; font-size: 11pt; }
#nav::item:hover { background: #1e293b; color: #ffffff; }
#nav::item:selected { background: #2563eb; color: #ffffff; }
#title { font-size: 20pt; font-weight: 700; }
#clock { color: #475569; font-size: 11pt; font-weight: 600; }
#h2 { font-size: 13pt; font-weight: 700; }
#muted { color: #64748b; }
#card, QGroupBox { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 14px; }
QGroupBox { margin-top: 16px; padding: 18px 14px 12px 14px; font-weight: 700; font-size: 11pt; }
QGroupBox::title { subcontrol-origin: margin; left: 16px; padding: 0 6px; color: #1e293b; }
#kpiTitle { color: #64748b; font-size: 9pt; font-weight: 700; letter-spacing: 1px; }
#kpiValue { font-size: 26pt; font-weight: 700; }
#tile { background: #0b1220; border-radius: 14px; }
#tile QLabel { color: #e2e8f0; }
#tileName { font-weight: 700; font-size: 11.5pt; }
#video { background: #020617; border-radius: 10px; color: #64748b; font-size: 12pt; }
QPushButton { background: #ffffff; border: 1px solid #cbd5e1; border-radius: 9px; padding: 8px 16px; font-weight: 600; }
QPushButton:hover { background: #f8fafc; border-color: #94a3b8; }
QPushButton:pressed { background: #e2e8f0; }
QPushButton:disabled { color: #94a3b8; background: #f1f5f9; border-color: #e2e8f0; }
QPushButton[kind="primary"] { background: #2563eb; border: none; color: #ffffff; }
QPushButton[kind="primary"]:hover { background: #1d4ed8; }
QPushButton[kind="primary"]:disabled { background: #93c5fd; }
QPushButton[kind="stop"] { background: #dc2626; border: none; color: #ffffff; }
QPushButton[kind="stop"]:hover { background: #b91c1c; }
QPushButton[kind="danger"] { color: #dc2626; border-color: #fecaca; }
QPushButton[kind="danger"]:hover { background: #fef2f2; }
QLineEdit, QComboBox, QSpinBox, QDoubleSpinBox, QDateEdit, QTimeEdit { background: #ffffff; border: 1px solid #cbd5e1;
  border-radius: 8px; padding: 6px 8px; min-height: 22px; selection-background-color: #bfdbfe; selection-color: #0f172a; }
QLineEdit:focus, QComboBox:focus, QSpinBox:focus, QDoubleSpinBox:focus, QDateEdit:focus, QTimeEdit:focus { border: 2px solid #3b82f6; }
QComboBox::drop-down, QDateEdit::drop-down { subcontrol-origin: padding; subcontrol-position: center right; width: 28px; border: none; }
QComboBox::down-arrow, QDateEdit::down-arrow { image: url("CHEVRON"); width: 12px; height: 8px; }
QComboBox QAbstractItemView { background: #ffffff; border: 1px solid #cbd5e1; selection-background-color: #dbeafe; selection-color: #0f172a; outline: none; }
QCheckBox::indicator { width: 18px; height: 18px; border: 2px solid #94a3b8; border-radius: 5px; background: #ffffff; }
QCheckBox::indicator:checked { background: #2563eb; border-color: #2563eb; image: url("CHECK"); }
QTableWidget::item { padding-left: 8px; }
QTableWidget { background: #ffffff; alternate-background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px;
  selection-background-color: #dbeafe; selection-color: #0f172a; }
QHeaderView::section { background: #f8fafc; color: #475569; font-weight: 700; padding: 9px 8px; border: none;
  border-bottom: 1px solid #e2e8f0; }
QTabWidget::pane { border: none; }
QTabBar::tab { background: transparent; color: #64748b; padding: 9px 22px; font-size: 11pt; border-bottom: 3px solid transparent; }
QTabBar::tab:selected { color: #2563eb; border-bottom: 3px solid #2563eb; }
QTabBar::tab:hover { color: #1e293b; }
#events::item { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 10px; margin: 3px 2px; }
QProgressBar { border: none; background: #e2e8f0; border-radius: 7px; min-height: 14px; max-height: 14px; text-align: center;
  font-size: 8pt; color: #0f172a; }
QProgressBar::chunk { background: #2563eb; border-radius: 7px; }
QScrollArea { border: none; background: transparent; }
QScrollBar:vertical { width: 10px; background: transparent; margin: 2px; }
QScrollBar::handle:vertical { background: #cbd5e1; border-radius: 4px; min-height: 30px; }
QScrollBar:horizontal { height: 10px; background: transparent; margin: 2px; }
QScrollBar::handle:horizontal { background: #cbd5e1; border-radius: 4px; min-width: 30px; }
QScrollBar::add-line, QScrollBar::sub-line { width: 0; height: 0; }
QCheckBox { spacing: 8px; }
QToolTip { background: #0f172a; color: #ffffff; border: none; padding: 6px; border-radius: 6px; }
"""


# ------------------------------------------------------------------ helpers
def _icon(name, w, h, color, width, points):  # tiny PNG for QSS (arrows / check marks), drawn at runtime
    pm = QPixmap(w, h); pm.fill(Qt.transparent); p = QPainter(pm); p.setRenderHint(QPainter.Antialiasing)
    p.setPen(QPen(QColor(color), width, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)); p.drawPolyline(QPolygonF([QPointF(*q) for q in points])); p.end()
    path = os.path.join(tempfile.gettempdir(), "faceattend_%s.png" % name); pm.save(path); return path.replace("\\", "/")


def apply_theme():  # once per application (login and main window both ask for it)
    app = QApplication.instance()
    if not app.styleSheet():
        app.setStyleSheet(THEME.replace("UIFONT", "Segoe UI" if os.name == "nt" else "Noto Sans").replace("CHEVRON", _icon("chevron", 12, 8, "#475569", 2, [(1, 1.5), (6, 6.5), (11, 1.5)]))
                          .replace("CHECK", _icon("check", 14, 14, "#ffffff", 2.2, [(3, 7.5), (6, 10.5), (11.5, 3.5)])))


def mtime(path): return os.path.getmtime(path) if path and os.path.exists(path) else 0


@lru_cache(maxsize=4096)
def avatar(name, photo, stamp, size=38):
    """Round photo (stamp = its mtime, 0 = none), or coloured circle with initials. Cached: tables are refilled often."""
    pm = QPixmap(size, size); pm.fill(Qt.transparent); p = QPainter(pm); p.setRenderHint(QPainter.Antialiasing)
    clip = QPainterPath(); clip.addEllipse(QRectF(0, 0, size, size)); p.setClipPath(clip)
    if stamp: p.drawPixmap(0, 0, QPixmap(photo).scaled(size, size, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation))
    else:
        p.fillRect(0, 0, size, size, QColor(["#2563eb", "#16a34a", "#d97706", "#7c3aed", "#0891b2", "#db2777"][sum(map(ord, name)) % 6]))
        f = QFont(); f.setBold(True); f.setPixelSize(size * 2 // 5); p.setFont(f); p.setPen(Qt.white)
        p.drawText(QRectF(0, 0, size, size), Qt.AlignCenter, "".join(w[0] for w in name.split()[:2]).upper())
    p.end(); return QIcon(pm)


def lay(cls, *items, parent=None, margins=None, spacing=None):
    """Layout builder: None = spacer, int = stretch of previous item, str = label, (text, slot[, kind]) = button, layout/widget."""
    l = cls(parent) if parent else cls()
    if margins is not None: l.setContentsMargins(*([margins] * 4 if isinstance(margins, int) else margins))
    if spacing is not None: l.setSpacing(spacing)
    for i in items:
        if i is None: l.addStretch(1)
        elif isinstance(i, int): l.setStretch(l.count() - 1, i)
        elif isinstance(i, str): l.addWidget(QLabel(i))
        elif isinstance(i, tuple): l.addWidget(button(*i))
        elif isinstance(i, QLayout): l.addLayout(i)
        else: l.addWidget(i)
    return l


def button(text, slot=None, kind=""):
    b = QPushButton(text, cursor=Qt.PointingHandCursor); b.setProperty("kind", kind)
    if slot: b.clicked.connect(slot)
    return b


def set_kind(b, kind): b.setProperty("kind", kind); b.style().unpolish(b); b.style().polish(b)
def card(): return QFrame(objectName="card")
def label(text="", name="", **kw): return QLabel(text, objectName=name, **kw)


def make(kind, extra=None, value=None):
    """Input widget by kind: text|password|edit|choice|bool|int|float|time|date."""
    if kind == "float": w = QDoubleSpinBox(); w.setRange(*extra[:2]); w.setSingleStep(extra[2]); w.setDecimals(extra[3])
    elif kind == "int": w = QSpinBox(); w.setRange(*extra)
    elif kind == "bool": w = QCheckBox()
    elif kind == "time": w = QTimeEdit(); w.setDisplayFormat("HH:mm:ss" if extra else "HH:mm")
    elif kind == "date": w = QDateEdit(QDate.currentDate(), calendarPopup=True); w.setDisplayFormat("yyyy-MM-dd")
    elif kind in ("choice", "edit"):
        w = QComboBox(editable=kind == "edit")
        for it in extra or []: w.addItem(*(it if isinstance(it, tuple) else (it, it)))
    else: w = QLineEdit(echoMode=QLineEdit.Password if kind == "password" else QLineEdit.Normal)
    if isinstance(w, QAbstractSpinBox) and not isinstance(w, QDateEdit): w.setButtonSymbols(QAbstractSpinBox.NoButtons)
    if value is not None: setv(w, value)
    return w


def getv(w):
    if isinstance(w, (QSpinBox, QDoubleSpinBox)): return w.value()
    if isinstance(w, QCheckBox): return w.isChecked()
    if isinstance(w, QTimeEdit): return w.time().toString(w.displayFormat())
    if isinstance(w, QDateEdit): return w.date().toString("yyyy-MM-dd")
    if isinstance(w, QComboBox): return w.currentText().strip() if w.isEditable() else w.currentData()
    return w.text().strip()


def setv(w, v):
    if isinstance(w, (QSpinBox, QDoubleSpinBox)): w.setValue(v)
    elif isinstance(w, QCheckBox): w.setChecked(bool(v))
    elif isinstance(w, QTimeEdit): w.setTime(QTime.fromString(v, w.displayFormat()))
    elif isinstance(w, QDateEdit): w.setDate(QDate.fromString(v, "yyyy-MM-dd"))
    elif isinstance(w, QComboBox): i = w.findData(v); w.setCurrentIndex(i) if i >= 0 else w.setCurrentText(str(v or ""))
    else: w.setText(str(v or ""))


class Form(QDialog):
    def __init__(self, parent, title, fields, values, check):
        super().__init__(parent); self.setWindowTitle(title); self.check = check; self.setMinimumWidth(420)
        f = QFormLayout(self); f.setContentsMargins(24, 20, 24, 20); f.setVerticalSpacing(12); f.setHorizontalSpacing(16)
        f.addRow(label(title, "h2")); self.w = {}
        for key, text, kind, extra in fields: self.w[key] = make(kind, extra, values.get(key)); f.addRow(text, self.w[key])
        bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel); bb.accepted.connect(self.ok); bb.rejected.connect(self.reject)
        set_kind(bb.button(QDialogButtonBox.Ok), "primary"); f.addRow(bb)

    def values(self): return {k: getv(w) for k, w in self.w.items()}

    def ok(self):
        err = self.check and self.check(self.values())
        QMessageBox.warning(self, self.windowTitle(), err) if err else self.accept()


def ask(parent, title, fields, values=None, check=None):
    """Form dialog. fields: [(key, label, kind, extra)]; check(values) -> error text or None. Returns values or None."""
    f = Form(parent, title, fields, values or {}, check); return f.values() if f.exec_() else None


def confirm(parent, title, text): return QMessageBox.question(parent, title, text) == QMessageBox.Yes


def table(row_h=38):
    t = QTableWidget(); t.setSelectionBehavior(t.SelectRows); t.setSelectionMode(t.SingleSelection); t.setEditTriggers(t.NoEditTriggers)
    t.setAlternatingRowColors(True); t.setShowGrid(False); t.verticalHeader().hide(); t.verticalHeader().setDefaultSectionSize(row_h)
    t.horizontalHeader().setStretchLastSection(True); t.horizontalHeader().setHighlightSections(False); t.horizontalHeader().setDefaultAlignment(Qt.AlignLeft | Qt.AlignVCenter); t.setFocusPolicy(Qt.NoFocus)
    return t


def fill(t, headers, rows, data=()):
    """Fill a table (status words colored); data[i] is stored on row i (read back with sel)."""
    bold = QFont(); bold.setBold(True)
    t.setSortingEnabled(False); t.clear(); t.setColumnCount(len(headers)); t.setHorizontalHeaderLabels(headers); t.setRowCount(len(rows))
    for r, row in enumerate(rows):
        for c, v in enumerate(row):
            it = QTableWidgetItem(); it.setData(Qt.DisplayRole, v if isinstance(v, (int, float)) else str(v or "")); it.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)
            if isinstance(v, str) and v in TAGS: it.setForeground(QColor(TAGS[v])); it.setFont(bold)
            if c == 0 and r < len(data): it.setData(Qt.UserRole, data[r])
            t.setItem(r, c, it)
    t.setSortingEnabled(True); t.resizeColumnsToContents()
    for c in range(t.columnCount()): t.setColumnWidth(c, t.columnWidth(c) + 24)


def sel(t, parent=None, what="a row"):
    r = t.selectionModel().selectedRows(); v = t.item(r[0].row(), 0).data(Qt.UserRole) if r else None
    if v is None and parent: QMessageBox.information(parent, "Select", "Select %s first." % what)
    return v


def draw(img, overlays, s=1.0):
    """Face boxes with bold corners and a filled name tag."""
    t, fs = max(2, img.shape[0] // 300), max(0.5, img.shape[0] / 1100)
    for box, text, color in overlays:
        x1, y1, x2, y2 = (int(v * s) for v in box); n = max(8, (x2 - x1) // 4)
        cv2.rectangle(img, (x1, y1), (x2, y2), color, 1, cv2.LINE_AA)
        for px, py, dx, dy in ((x1, y1, 1, 1), (x2, y1, -1, 1), (x1, y2, 1, -1), (x2, y2, -1, -1)):
            cv2.line(img, (px, py), (px + dx * n, py), color, t + 1, cv2.LINE_AA); cv2.line(img, (px, py), (px, py + dy * n), color, t + 1, cv2.LINE_AA)
        if text:
            (tw, th), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_DUPLEX, fs, 1); top = max(0, y1 - th - 14)
            cv2.rectangle(img, (x1, top), (x1 + tw + 14, top + th + 12), color, -1)
            cv2.putText(img, text, (x1 + 7, top + th + 5), cv2.FONT_HERSHEY_DUPLEX, fs, (255, 255, 255), 1, cv2.LINE_AA)


def show(lbl, frame, overlays=()):
    """Fit a BGR frame into a QLabel (shrink first, then draw + convert: cheap)."""
    h, w = frame.shape[:2]; s = min(lbl.width() / w, lbl.height() / h)
    if s <= 0: return
    for _ in range(int(-math.log2(s))): frame = cv2.resize(frame, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)  # fast 2x2 means
    img = cv2.resize(frame, (max(1, int(w * s)), max(1, int(h * s))), interpolation=cv2.INTER_AREA if s < 1 else cv2.INTER_LINEAR)
    draw(img, overlays, s); rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    lbl.setPixmap(QPixmap.fromImage(QImage(rgb.data, rgb.shape[1], rgb.shape[0], rgb.strides[0], QImage.Format_RGB888)))  # pixmap copies


def video_label(text="", w=320, h=180):
    l = label(text, "video", alignment=Qt.AlignCenter, minimumSize=QSize(w, h)); l.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
    return l


def pill(lbl, text, color):  # coloured status badge
    if getattr(lbl, "badge", None) == (text, color): return  # unchanged (asked every video frame): restyling is slow
    lbl.badge = (text, color); lbl.setText(" ● " + text.upper() + " ")
    c = QColor(color)  # note: Qt reads 8-digit hex as #AARRGGBB, so use rgba()
    lbl.setStyleSheet("color:%s; background:rgba(%d,%d,%d,40); border-radius:9px; padding:3px 8px; font-weight:700; font-size:8.5pt;"
                      % (color, c.red(), c.green(), c.blue()))


class Worker(QThread):
    """Runs fn(report) in the background; done(result) / fail(message) / progress(text) arrive in the slots' (GUI) thread.
    Slots must be bound methods of GUI objects, never lambdas (those would run in the worker thread)."""
    done, fail, progress = pyqtSignal(object), pyqtSignal(str), pyqtSignal(str)

    def __init__(self, fn, done, fail=log.debug, progress=None):
        super().__init__(); self.fn = fn; self.done.connect(done); self.fail.connect(fail)
        if progress: self.progress.connect(progress)
        self.start()

    def run(self):
        try: self.done.emit(self.fn(self.progress.emit))
        except Exception as e: log.exception("background task failed"); self.fail.emit(str(e))


# ------------------------------------------------------------- login/context
def set_password(parent, cfg, first=False):
    v = ask(parent, "Create admin account" if first else "Change admin password",
            [("user", "Username", "text", None), ("pw", "New password", "password", None), ("pw2", "Repeat", "password", None)],
            {"user": cfg.get("admin.username")}, lambda v: "Username required." if not v["user"] else "Use at least 6 characters."
            if len(v["pw"]) < 6 else "Passwords differ." if v["pw"] != v["pw2"] else None)
    if v: cfg.set("admin.username", v["user"]); cfg.set("admin.password_hash", hash_password(v["pw"])); cfg.save()
    return v is not None


def login(cfg):
    apply_theme()
    if not cfg.get("admin.require_login"): return True
    if not cfg.get("admin.password_hash"): return set_password(None, cfg, True)
    tries = [0]
    def check(v):
        if v["user"] == cfg.get("admin.username") and verify_password(v["pw"], cfg.get("admin.password_hash")): return None
        tries[0] += 1
        if tries[0] >= 5: sys.exit(1)
        return "Wrong username or password."
    return ask(None, "Sign in to FaceAttend", [("user", "Username", "text", None), ("pw", "Password", "password", None)],
               {"user": cfg.get("admin.username")}, check) is not None


class Ctx(QObject):
    """Shared objects. `changed` = data changed, pages refresh."""
    ready, failed, changed, progress = pyqtSignal(), pyqtSignal(str), pyqtSignal(), pyqtSignal(str)  # ready: engine (re)loaded

    def __init__(self, cfg):
        super().__init__(); self.cfg, self.data, self.engine, self.loading = cfg, cfg.dir("data"), None, True  # loading: an engine is being made
        self.db = Database(os.path.join(self.data, "attendance.db")); self.gallery = Gallery(cfg); self.gallery.load(self.db)
        self.att, self.cams, self.live = Attendance(self.db, cfg, self.data), CameraManager(cfg), None

    def refresh(self): self.gallery.load(self.db); self.changed.emit()
    def load_engine(self): self.loader = Worker(lambda report: load_engine(self.cfg, self.db, None, report), self._loaded, self._failed, self.progress)
    def _loaded(self, engine): self.engine, self.loading = engine, False; self.ready.emit()
    def _failed(self, msg): self.loading = False; self.failed.emit(msg)

    def need_engine(self, parent):  # not while it loads or the model is being switched
        ok = self.engine is not None and not self.loading
        if not ok: QMessageBox.information(parent, "Please wait", "The face engine is still loading.")
        return ok


# ----------------------------------------------------------------- threads
class Pipeline(QThread):
    """Per camera: newest frame -> faces -> matches -> tracks -> attendance. Overlays are read by the GUI timer."""
    event, painted = pyqtSignal(dict), (None, None)  # painted: what LiveTab.paint drew last
    def __init__(self, ctx, cam, stream): super().__init__(); self.ctx, self.cam, self.stream, self.overlays, self.fps, self.on = ctx, cam, stream, [], 0.0, True
    def stop(self): self.on = False; self.wait(5000)

    def run(self):
        t = self.ctx.cfg.get("tracking"); tracker = Tracker(t["iou"], t["max_missed"], t["window"], t["votes"], self.ctx.cfg.get("profile.gate"))
        last, n, t0 = -1, 0, time.time()
        while self.on:
            start = time.time(); frame, fid, ts = self.stream.read()
            if frame is None or fid == last:
                if self.overlays and time.time() - ts > 2: self.overlays = []
                time.sleep(0.02); continue
            last = fid
            try: self.overlays = self.step(frame, tracker)
            except Exception: log.exception("pipeline %s", self.cam["name"]); time.sleep(1)
            n += 1
            if time.time() - t0 >= 2: self.fps, n, t0 = n / (time.time() - t0), 0, time.time()
            time.sleep(max(0, 1 / self.ctx.cfg.get("camera.process_fps") - (time.time() - start)))

    def step(self, frame, tracker):
        faces, g, out = self.ctx.engine.analyze(frame, embed_all=True), self.ctx.gallery, []  # all embedded: track gate
        it = iter(g.match([f.emb for f in faces if f.ok]))  # only good-quality faces vote
        for tr in tracker.update(faces, [next(it) if f.ok else None for f in faces]):
            st, p = tr.state, g.people.get(tr.identity, {})
            if st in ("known", "unknown") and not tr.marked:
                tr.marked = True
                ev = self.ctx.att.process(tr.identity, p.get("name", "?"), p.get("emp_code", ""), self.cam, tr.sim, tr.face.bgr()) \
                    if st == "known" else self.ctx.att.unknown(self.cam, tr.sim, tr.face.bgr())
                if ev: self.event.emit(ev)
            text = {"known": "%s  %.0f%%" % (p.get("name", "?"), tr.sim * 100), "unknown": "Unknown", "pending": "Identifying...",
                    "low_quality": (tr.face.reasons or ["low quality"])[0]}[st]
            out.append((tr.box, text, COLORS[st]))
        return out


class EnrollWorker(QThread):
    frame, progress = pyqtSignal(object), pyqtSignal(int, str)
    def __init__(self, ctx, stream, col): super().__init__(); self.ctx, self.stream, self.col, self.capturing, self.on = ctx, stream, col, False, True
    def stop(self): self.on = False; self.wait(5000)

    def run(self):
        last, t_cap, gap = -1, 0.0, self.ctx.cfg.get("enrollment.interval_sec")
        while self.on:
            frame, fid, _ = self.stream.read()
            if frame is None or fid == last: time.sleep(0.03); continue
            last, cap, view = fid, self.capturing, frame.copy()  # cap: read once per frame, the GUI thread flips it at any moment
            try: faces = self.ctx.engine.analyze(frame, chips=cap)  # chips: stored with the samples
            except Exception: log.exception("enrollment"); time.sleep(1); continue
            msg = "No face - look at the camera" if not faces else "Only one person in view please" if len(faces) > 1 else ""
            if len(faces) == 1:
                f = faces[0]; draw(view, [(f.box, "", COLORS["known"] if f.ok else COLORS["pending"])])
                if cap and time.time() - t_cap >= gap:
                    ok, msg = self.col.offer(f); t_cap = time.time() if ok else t_cap
                elif not f.ok: msg = ", ".join(f.reasons)
            if self.col.done: self.capturing, msg = False, "All samples captured - press Save."
            self.frame.emit(view); self.progress.emit(len(self.col.embs), msg)


# -------------------------------------------------------------------- pages
class Page(QWidget):
    """Base page. Reloads on data changes only while visible (a hidden page catches up when shown); row actions for self.t."""
    TABLE = WHAT = ""  # database table listed in self.t, and what one row of it is called

    def __init__(self, ctx): super().__init__(); self.ctx, self.stale = ctx, False; ctx.changed.connect(self.changed)
    def changed(self): self.stale = True; self.showEvent()

    def showEvent(self, e=None):
        if self.stale and self.isVisible(): self.stale = False; self.reload()

    def current(self):  # selected row as a database row
        rid = sel(self.t, self, self.WHAT); return rid and self.ctx.db.get(self.TABLE, rid)

    def edit(self, *_):
        row = self.current()
        if row: self.form(row)

    def remove(self, text, table=None, col="id", title="Delete"):  # confirm, then delete what belongs to the selected row
        row = self.current()
        if row and confirm(self, title, text % row): self.ctx.db.delete(table or self.TABLE, row["id"], col); self.ctx.refresh()


class LiveTab(Page):
    def __init__(self, ctx):
        super().__init__(ctx); self.views, self.pipes, self.running = {}, {}, False
        self.btn = button("▶  Start monitoring", self.toggle, "primary"); self.btn.setEnabled(False); self.btn.setMinimumHeight(40)
        self.info, self.grid, self.kpis = label("Waiting for the face engine...", "muted"), QGridLayout(), {}
        self.grid.setSpacing(14)
        cards = []
        for key, title, color in (("total", "Employees", "#0f172a"), ("present", "Present", "#16a34a"), ("late", "Late", "#d97706"),
                                  ("absent", "Absent", "#dc2626"), ("out", "Checked out", "#2563eb")):
            c, v = card(), label("0", "kpiValue", styleSheet="color:" + color); self.kpis[key] = v
            lay(QVBoxLayout, label(title.upper(), "kpiTitle"), v, parent=c, margins=(18, 14, 18, 14), spacing=2); cards.append(c)
        self.events = QListWidget(objectName="events"); self.events.setVerticalScrollMode(QListWidget.ScrollPerPixel)
        side = card(); side.setFixedWidth(360)
        lay(QVBoxLayout, lay(QHBoxLayout, label("Recent events", "h2"), None, ("Clear", self.events.clear)), self.events, 1, parent=side, margins=14)
        lay(QVBoxLayout, lay(QHBoxLayout, *cards, spacing=14), lay(QHBoxLayout, self.btn, self.info, None, spacing=14),
            lay(QHBoxLayout, self.grid, 1, side, spacing=14), 1, parent=self, margins=0, spacing=14)
        self.timer = QTimer(self, timeout=self.paint); QTimer(self, timeout=self.stats).start(15000)
        ctx.ready.connect(self.on_ready); ctx.progress.connect(self.info.setText); self.reload()

    def on_ready(self):
        self.btn.setEnabled(True); self.info.setText("Ready - press Start to recognize faces on %d camera(s)." % len(self.ctx.db.cameras(True)))

    def reload(self):
        self.stats()
        if not self.running: self.build()

    def build(self):
        while self.grid.count(): w = self.grid.takeAt(0).widget(); w.hide(); w.deleteLater()  # hide now: deletion is deferred
        cams, self.views = self.ctx.db.cameras(True), {}
        if not cams:
            empty = card(); lay(QVBoxLayout, None, label("No cameras yet", "h2", alignment=Qt.AlignCenter),
                                label("Add an RTSP camera on the Cameras page.", "muted", alignment=Qt.AlignCenter), None, parent=empty)
            self.grid.addWidget(empty, 0, 0)
        cols = math.ceil(math.sqrt(len(cams))) or 1
        for i, c in enumerate(cams):
            tile, status, fps, video = QFrame(objectName="tile"), QLabel(), label("", "muted"), video_label("Stopped")
            role = label(c["role"].upper(), styleSheet="color:#93c5fd; background:#1e3a8a; border-radius:6px; padding:2px 8px; font-size:8pt; font-weight:700")
            pill(status, "stopped", STREAM["stopped"]); self.views[c["id"]] = (c, video, status, fps)
            lay(QVBoxLayout, lay(QHBoxLayout, label(c["name"], "tileName"), role, None, status), video, 1, fps, parent=tile, margins=12, spacing=8)
            self.grid.addWidget(tile, i // cols, i % cols)

    def toggle(self):
        if not self.running and not self.ctx.need_engine(self): return
        if self.running:
            self.timer.stop()
            for cid, p in self.pipes.items(): p.stop(); self.ctx.cams.release(cid)
            self.pipes, self.running = {}, False; self.build()
        else:
            self.build()
            for cid, (cam, *_) in self.views.items():
                p = self.pipes[cid] = Pipeline(self.ctx, cam, self.ctx.cams.acquire(cam)); p.event.connect(self.on_event); p.start()
            self.timer.start(int(1000 / self.ctx.cfg.get("camera.display_fps"))); self.running = True
        self.btn.setText("■  Stop monitoring" if self.running else "▶  Start monitoring"); set_kind(self.btn, "stop" if self.running else "primary")
        self.info.setText("Monitoring %d camera(s)" % len(self.pipes) if self.running else "Stopped")

    def paint(self):
        if not self.isVisible() or self.window().isMinimized(): return  # nobody sees the video
        for cid, p in self.pipes.items():
            (_, video, status, fps), s = self.views[cid], p.stream; pill(status, s.status, STREAM[s.status])
            fps.setText("Stream %.1f fps  ·  Recognition %.1f fps  ·  %d face(s)" % (s.fps, p.fps, len(p.overlays)))
            if not s.alive(): video.setText(s.status.capitalize() + "..."); p.painted = (None, None); continue
            frame, fid, _ = s.read(); ov = p.overlays; key = (fid, id(ov), video.width(), video.height())
            if key != p.painted[0]: p.painted = (key, ov); show(video, frame, ov)  # same frame, boxes and size: nothing to redraw

    def on_event(self, e):
        w = QWidget(); pic = QLabel(styleSheet="background:#e2e8f0; border-radius:8px"); pic.setFixedSize(56, 56)
        if e["snapshot_path"]: pic.setPixmap(QPixmap(e["snapshot_path"]).scaled(56, 56, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation))
        late = " <span style='color:#d97706; font-weight:700'>LATE</span>" if e["status"] == "Late" and e["event_type"] == "check_in" else ""
        info = QLabel("<span style='font-size:11pt; font-weight:700'>%s</span> <span style='color:#64748b'>%s</span><br>"
                      "<span style='color:%s; font-weight:700'>%s</span>%s<br><span style='color:#64748b'>%s  ·  %s  ·  %.0f%%</span>"
                      % (e["name"], e["emp_code"], TAGS[e["event_type"]], e["event_type"].replace("_", " ").upper(), late, e["timestamp"][11:],
                         e["camera_name"], e["similarity"] * 100))
        lay(QHBoxLayout, pic, info, 1, parent=w, margins=8, spacing=12)
        it = QListWidgetItem(); it.setSizeHint(QSize(300, 90)); self.events.insertItem(0, it); self.events.setItemWidget(it, w)
        if self.events.count() > 200: self.events.takeItem(200)
        if e["event_type"] in ("check_in", "check_out"): self.ctx.changed.emit()

    def stats(self):
        s = self.ctx.db.stats(date.today().isoformat()); s["absent"] = max(0, s["total"] - s["present"])
        for k, v in s.items(): self.kpis[k].setText(str(v))


def save_faces(parent, ctx, emp, faces, source, photo):
    mean = np.mean([f.emb for f in faces], 0); m = ctx.gallery.match([mean / np.linalg.norm(mean)])[0]
    if m.known and m.id != emp["id"] and not confirm(parent, "Possible duplicate", "These faces look like %s (%s), similarity %.2f. "
                                                     "Save anyway?" % (m.name, m.code, m.sim)): return False
    ctx.db.add_faces(emp["id"], ctx.engine.key, faces, source)
    if photo is not None:
        d = os.path.join(ctx.data, "faces"); os.makedirs(d, exist_ok=True); p = os.path.join(d, "%d.jpg" % emp["id"])
        imwrite(p, photo); ctx.db.update("employees", emp["id"], photo_path=p)
    ctx.refresh(); QMessageBox.information(parent, "Enrollment", "Saved %d face samples for %s." % (len(faces), emp["name"]))
    return True


class EnrollDialog(QDialog):
    def __init__(self, ctx, emp, parent):
        super().__init__(parent); self.ctx, self.emp, self.worker, self.cid = ctx, emp, None, None
        e = ctx.cfg.get("enrollment"); self.col = Collector(e["samples"], e["max_sim"], ctx.cfg.get("profile.min_same"))
        self.setWindowTitle("Enroll face"); self.resize(900, 720)
        self.cam = QComboBox()
        for c in ctx.db.cameras(): self.cam.addItem(c["name"], c)
        self.video, self.msg, self.bar = video_label("Select a camera and press Connect", 640, 400), label("", "h2"), QProgressBar(maximum=e["samples"])
        self.bar.setFormat("%v / %m samples")
        self.cap_btn, self.save_btn = button("Start capture", self.toggle), button("Save", self.save, "primary")
        self.cap_btn.setEnabled(False); self.save_btn.setEnabled(False)
        tips = label("Look straight at the camera, then slowly turn your head a little left, right, up and down. "
                     "Only the person being enrolled may be in view.", "muted", wordWrap=True)
        lay(QVBoxLayout, label("Enroll %s  (%s)" % (emp["name"], emp["emp_code"]), "title"),
            lay(QHBoxLayout, "Camera", self.cam, 1, ("Connect", self.connect_cam, "primary")), self.video, 1, tips, self.msg, self.bar,
            lay(QHBoxLayout, self.cap_btn, ("Reset", self.reset), None, self.save_btn, ("Close", self.reject)), parent=self, margins=20, spacing=12)

    def connect_cam(self):
        self.release(); cam = self.cam.currentData()
        if cam is None: return
        self.cid, self.worker = cam["id"], EnrollWorker(self.ctx, self.ctx.cams.acquire(cam), self.col)
        self.worker.frame.connect(self.show_frame); self.worker.progress.connect(self.progress); self.worker.start(); self.cap_btn.setEnabled(True)

    def show_frame(self, f): show(self.video, f)
    def toggle(self): self.worker.capturing = not self.worker.capturing
    def reset(self): self.col.reset(); self.progress(0, "")
    def save(self): save_faces(self, self.ctx, self.emp, self.col.faces, "camera", self.col.best) and self.accept()

    def progress(self, n, msg):
        good = msg.startswith(("captured", "All samples"))
        self.bar.setValue(n); self.msg.setText(msg); self.msg.setStyleSheet("color:" + ("#16a34a" if good else "#d97706"))
        self.save_btn.setEnabled(n >= max(3, self.col.target // 3))
        self.cap_btn.setText("Pause capture" if self.worker and self.worker.capturing else "Start capture")

    def release(self):
        if self.worker: self.worker.stop(); self.worker = None
        if self.cid is not None: self.ctx.cams.release(self.cid); self.cid = None

    def done(self, r): self.release(); super().done(r)


EMP_FIELDS = [("emp_code", "Employee code *", "text", None), ("name", "Full name *", "text", None), ("department", "Department", "edit", None),
              ("designation", "Designation", "text", None), ("email", "Email", "text", None), ("phone", "Phone", "text", None),
              ("active", "Active (recognized)", "bool", None)]


class EmployeesTab(Page):
    TABLE, WHAT, COLS = "employees", "an employee", ("emp_code", "name", "department", "designation", "email", "phone", "face_count")

    def __init__(self, ctx):
        super().__init__(ctx); self.t = table(48)
        self.search = QLineEdit(placeholderText="🔍  Search name, code or department...", minimumWidth=220); self.search.textChanged.connect(self.reload)
        self.t.doubleClicked.connect(self.edit); self.t.setIconSize(QSize(38, 38))
        lay(QVBoxLayout, lay(QHBoxLayout, self.search, None, ("+  Add employee", self.form, "primary"), ("Edit", self.edit),
                             ("Enroll (camera)", self.enroll_cam), ("Enroll (photos)", self.enroll_img), ("Clear faces", self.clear, "danger"),
                             ("Delete", self.delete, "danger"), spacing=8), self.t, 1, parent=self, margins=0, spacing=14)
        self.reload()

    def reload(self, *_):
        people = {e["id"]: e for e in self.ctx.db.employees(self.search.text().strip())}
        fill(self.t, ["Code", "Name", "Department", "Designation", "Email", "Phone", "Face samples", "Active"],
             [[e[k] for k in self.COLS] + [("No", "Yes")[e["active"]]] for e in people.values()], list(people))
        for r in range(self.t.rowCount()):  # rows may be sorted now: find each one's employee by its id
            it = self.t.item(r, 0); e = people[it.data(Qt.UserRole)]; it.setIcon(avatar(e["name"], e["photo_path"], mtime(e["photo_path"])))
        self.t.setColumnWidth(0, self.t.columnWidth(0) + 44)

    def form(self, emp=None):  # add (then offer enrollment) or edit
        fields = EMP_FIELDS[:2] + [("department", "Department", "edit", [""] + self.ctx.db.departments())] + EMP_FIELDS[3:]
        def check(v):
            o = self.ctx.db.one("SELECT id FROM employees WHERE emp_code=?", (v["emp_code"],))
            return "Code and name are required." if not v["emp_code"] or not v["name"] else \
                "Employee code already exists." if o and (not emp or o["id"] != emp["id"]) else None
        v = ask(self, "Edit employee" if emp else "Add employee", fields, emp or {"active": True}, check)
        if not v: return
        if emp: self.ctx.db.update("employees", emp["id"], **v); return self.ctx.refresh()
        eid = self.ctx.db.add_employee(**v); self.ctx.refresh()
        if self.ctx.engine and confirm(self, "Enroll", "Enroll %s's face now?" % v["name"]): self.enroll_cam(self.ctx.db.get("employees", eid))

    def delete(self): self.remove("Delete %(name)s with face samples AND attendance history?\n(Untick 'Active' instead to keep the history.)")
    def clear(self): self.remove("Remove all face samples of %(name)s?", "faces", "employee_id", "Clear faces")

    def enroll_cam(self, emp=None):
        emp = emp or self.current()
        if emp and self.ctx.need_engine(self): EnrollDialog(self.ctx, emp, self).exec_()

    def enroll_img(self):
        e = self.current()
        if not e or not self.ctx.need_engine(self): return
        paths = QFileDialog.getOpenFileNames(self, "Face photos of " + e["name"], "", "Images (*.jpg *.jpeg *.png *.bmp)")[0]
        QApplication.setOverrideCursor(Qt.WaitCursor); faces, bad = [], []
        try:
            for p in paths:
                img = cv2.imdecode(np.fromfile(p, np.uint8), cv2.IMREAD_COLOR)  # works with non-ASCII paths
                f = self.ctx.engine.embed_image(img) if img is not None else None
                faces.append(f) if f else bad.append(os.path.basename(p))
        finally: QApplication.restoreOverrideCursor()
        if bad: QMessageBox.warning(self, "Photos", "No face found in: " + ", ".join(bad))
        if faces: save_faces(self, self.ctx, e, faces, "image", max(faces, key=lambda f: f.score).bgr())


class AttendanceTab(Page):
    TABLE, WHAT, LOG = "attendance", "a record in Daily records", ["Time", "Camera", "Emp Code", "Name", "Event", "Similarity", "Snapshot"]

    def __init__(self, ctx):
        super().__init__(ctx); self.rows, self.heads = [], []
        self.d1, self.d2, self.emp, self.dept = make("date"), make("date"), QComboBox(minimumWidth=180), QComboBox(minimumWidth=160)
        for d in (self.d1, self.d2): d.setMinimumWidth(130)
        self.status = make("choice", [("All statuses", "")] + STATUSES)
        self.absent = QCheckBox("Show absent", checked=True, toolTip="Single-day view: list employees with no record")
        self.month, self.year = make("int", (1, 12), date.today().month), make("int", (2000, 2100), date.today().year)
        self.tabs, self.daily, self.logs, self.monthly, self.info, mw = QTabWidget(), table(), table(), table(), label("", "h2"), QWidget()
        self.t = self.daily
        lay(QVBoxLayout, lay(QHBoxLayout, "Month", self.month, "Year", self.year, label("Sat/Sun are not counted as absent", "muted"), None),
            self.monthly, 1, parent=mw, margins=(0, 10, 0, 0))
        for w, name in ((self.daily, "Daily records"), (self.logs, "Recognition log"), (mw, "Monthly summary")): self.tabs.addTab(w, name)
        filters = card()
        lay(QHBoxLayout, "From", self.d1, "To", self.d2, self.emp, self.dept, self.status, self.absent, None, parent=filters, margins=12, spacing=10)
        lay(QVBoxLayout, filters, self.tabs, 1,
            lay(QHBoxLayout, self.info, None, ("+  Manual entry", self.form, "primary"), ("Edit record", self.edit), ("Delete record", self.delete, "danger"),
                ("Export CSV", lambda: self.export("csv")), ("Export Excel", lambda: self.export("xlsx")), spacing=8), parent=self, margins=0, spacing=12)
        for s in (self.tabs.currentChanged, self.month.valueChanged, self.year.valueChanged, self.d1.dateChanged, self.d2.dateChanged,
                  self.emp.activated, self.dept.activated, self.status.activated, self.absent.toggled): s.connect(self.refresh)
        self.logs.doubleClicked.connect(self.open_snap); self.daily.doubleClicked.connect(self.edit)
        self.reload()

    def reload(self):  # filter choices, then the tables
        e, d = self.emp.currentData(), self.dept.currentData()
        self.emp.clear(); self.emp.addItem("All employees", 0); self.dept.clear(); self.dept.addItem("All departments", "")
        for x in self.ctx.db.employees(): self.emp.addItem("%s (%s)" % (x["name"], x["emp_code"]), x["id"])
        for x in self.ctx.db.departments(): self.dept.addItem(x, x)
        self.emp.setCurrentIndex(max(0, self.emp.findData(e))); self.dept.setCurrentIndex(max(0, self.dept.findData(d))); self.refresh()

    def refresh(self, *_):
        (d1, d2), eid, dept, i = sorted([getv(self.d1), getv(self.d2)]), self.emp.currentData(), self.dept.currentData(), self.tabs.currentIndex()
        if i == 0:
            self.heads, (self.rows, ids) = DAILY, daily_rows(self.ctx.db, d1, d2, eid, dept, self.status.currentData(), self.absent.isChecked())
            fill(self.daily, DAILY, self.rows, ids)
            n = [sum(r[7] in s for r in self.rows) for s in (("Present", "Late"), ("Late",), ("Absent",))]
            self.info.setText("<span style='color:#16a34a'>Present %d</span>   <span style='color:#d97706'>Late %d</span>   "
                              "<span style='color:#dc2626'>Absent %d</span>" % tuple(n))
        elif i == 1:
            ls = self.ctx.db.logs(d1, d2, eid); self.heads = self.LOG
            self.rows = [[l["timestamp"], l["camera"], l["emp_code"], l["name"] or "Unknown", l["event_type"], l["similarity"],
                          "open" if l["snapshot_path"] else ""] for l in ls]
            fill(self.logs, self.LOG, self.rows, [l["snapshot_path"] for l in ls]); self.info.setText("%d events  ·  double-click opens the snapshot" % len(ls))
        else:
            self.heads, self.rows = MONTHLY, monthly_rows(self.ctx.db, self.year.value(), self.month.value(), dept)
            fill(self.monthly, MONTHLY, self.rows); self.info.setText("%d employees" % len(self.rows))

    def open_snap(self):
        p = sel(self.logs)
        if p and os.path.exists(p): QDesktopServices.openUrl(QUrl.fromLocalFile(p))

    def form(self, rec=None):  # manual entry, or correction of a record (it moves when employee or date change)
        rec = rec or {}
        fields = [("employee_id", "Employee", "choice", [("%s (%s)" % (e["name"], e["emp_code"]), e["id"]) for e in self.ctx.db.employees()]),
                  ("date", "Date", "date", None), ("has_in", "Has check-in", "bool", None), ("check_in", "Check-in", "time", 1),
                  ("has_out", "Has check-out", "bool", None), ("check_out", "Check-out", "time", 1), ("status", "Status", "choice", STATUSES),
                  ("note", "Reason *", "text", None)]
        vals = {**rec, "date": rec.get("date", date.today().isoformat()), "has_in": bool(rec.get("check_in", 1)), "has_out": bool(rec.get("check_out")),
                "check_in": (rec.get("check_in") or "")[11:] or "09:00:00", "check_out": (rec.get("check_out") or "")[11:] or "18:00:00"}
        v = ask(self, "Attendance entry", fields, vals, lambda v: "Enter a reason." if not v["note"] else "Select an employee."
                if v["employee_id"] is None else "Check-out is before check-in." if v["has_in"] and v["has_out"] and v["check_out"] < v["check_in"] else None)
        if not v: return
        if rec and (rec["employee_id"], rec["date"]) != (v["employee_id"], v["date"]): self.ctx.db.delete("attendance", rec["id"])
        self.ctx.db.mark(v["employee_id"], v["date"], check_in="%s %s" % (v["date"], v["check_in"]) if v["has_in"] else None,
                         check_out="%s %s" % (v["date"], v["check_out"]) if v["has_out"] else None, status=v["status"], manual=1, note=v["note"])
        self.ctx.changed.emit()

    def current(self): return self.tabs.currentIndex() == 0 and super().current()  # records are picked in Daily records only
    def delete(self): self.remove("Delete the attendance record of %(date)s?")

    def export(self, ext):
        name = "%s_%s.%s" % (self.tabs.tabText(self.tabs.currentIndex()).replace(" ", "_"), datetime.now().strftime("%Y%m%d_%H%M"), ext)
        p = QFileDialog.getSaveFileName(self, "Export", name)[0]
        try:
            if p: export(p, self.heads, self.rows); QMessageBox.information(self, "Export", "Saved " + p)
        except Exception as e: QMessageBox.critical(self, "Export", str(e))


CAM_FIELDS = [("name", "Name *", "text", None), ("url", "Stream URL *", "text", None),
              ("role", "Role", "choice", [("Both (first = check-in, later = check-out)", "both"), ("Entry (check-in)", "entry"),
                                          ("Exit (check-out)", "exit")]), ("enabled", "Enabled", "bool", None)]


class CamerasTab(Page):
    TABLE, WHAT, task = "cameras", "a camera", None

    def __init__(self, ctx):
        super().__init__(ctx); self.t, self.result, self.preview = table(), label("Select a camera and press Test connection", "muted"), video_label("No preview", 480, 270)
        self.t.doubleClicked.connect(self.edit)
        prev = card(); prev.setFixedWidth(520)
        lay(QVBoxLayout, label("Connection test", "h2"), self.preview, 1, self.result, ("⚡  Test connection", self.test, "primary"),
            label("RTSP examples:<br>Hikvision  rtsp://user:pass@IP:554/Streaming/Channels/101<br>"
                  "Dahua  rtsp://user:pass@IP:554/cam/realmonitor?channel=1&amp;subtype=0<br>Webcam  0  ·  Video file  /path/video.mp4", "muted", wordWrap=True),
            parent=prev, margins=16, spacing=10)
        lay(QVBoxLayout, lay(QHBoxLayout, ("+  Add camera", self.form, "primary"), ("Edit", self.edit), ("Delete", self.delete, "danger"), None, spacing=8),
            lay(QHBoxLayout, self.t, 1, prev, spacing=14), 1, parent=self, margins=0, spacing=14)
        self.reload()

    def reload(self):
        cs = self.ctx.db.cameras()
        fill(self.t, ["ID", "Name", "URL", "Role", "Enabled"], [[c["id"], c["name"], mask_url(c["url"]), c["role"], ("No", "Yes")[c["enabled"]]] for c in cs],
             [c["id"] for c in cs])

    def form(self, cam=None):
        v = ask(self, "Edit camera" if cam else "Add camera", CAM_FIELDS, cam or {"enabled": True},
                lambda v: None if v["name"] and v["url"] else "Name and URL are required.")
        if not v: return
        if cam: self.ctx.db.update("cameras", cam["id"], **v)
        else: self.ctx.db.insert("cameras", **v)
        self.ctx.changed.emit()

    def delete(self): self.remove("Delete camera '%(name)s'?")

    def test(self):
        c = self.current()
        if not c or (self.task and self.task.isRunning()): return  # one test at a time
        self.result.setText("Connecting to %s..." % c["name"]); self.result.setStyleSheet("")
        self.task = Worker(lambda report: probe(c["url"], self.ctx.cfg.get("camera.transport")), self.tested, self.test_failed)

    def test_failed(self, msg): self.tested((False, msg, None))

    def tested(self, r):
        ok, msg, f = r; self.result.setText(("✔  " if ok else "✖  ") + msg)
        self.result.setStyleSheet("font-weight:700; color:" + ("#16a34a" if ok else "#dc2626"))
        if f is not None: show(self.preview, f)


def stars(n, color="#f59e0b"): return "<span style='color:%s'>%s</span><span style='color:#cbd5e1'>%s</span>" % (color, "★" * n, "★" * (5 - n))


class ModelsTab(Page):
    """Pick the recognition model and its format (ONNX Runtime or PyTorch .pt). Downloads / conversions run in the background;
    switching converts every stored face (no re-enrollment)."""
    def __init__(self, ctx):
        super().__init__(ctx); self.cards, self.job = {}, None  # job: (model, runtime) being downloaded / switched to
        host = QWidget(objectName="page"); box = lay(QVBoxLayout, parent=host, margins=0, spacing=12)
        for key, m in MODELS.items():
            c, badge, files = card(), QLabel(), label("", "muted")
            rt = make("choice", [(v, k) for k, v in RUNTIMES.items()], ctx.cfg.get("runtime")); rt.currentIndexChanged.connect(self.reload)
            dl, use = button("⬇  Download", self.download), button("Use this model", self.use, "primary"); dl.key = use.key = key
            info = label("%s<br><span style='color:#64748b'>%s</span><br>Accuracy %s &nbsp;&nbsp; Speed %s &nbsp;&nbsp; %d MB &nbsp;&nbsp; "
                         "<span style='color:#64748b'>%s</span>" % (m["about"], m["arch"], stars(m["accuracy"]), stars(m["speed"], "#2563eb"), m["mb"], m["license"]), wordWrap=True)
            lay(QVBoxLayout, lay(QHBoxLayout, label(m["name"], "h2"), badge, None, rt, dl, use, spacing=8), info, files, parent=c, margins=16, spacing=6)
            box.addWidget(c); self.cards[key] = (badge, files, rt, dl, use)
        box.addStretch(1)
        self.note = label("Choose the face recognition model and its format: ONNX Runtime (faster on CPU) or the PyTorch model. Enrolled faces "
                          "are converted automatically when you switch - nobody has to enroll again.", "muted", wordWrap=True)
        sc = QScrollArea(widgetResizable=True); sc.setWidget(host)
        lay(QVBoxLayout, self.note, sc, 1, parent=self, margins=0, spacing=12)
        ctx.ready.connect(self.reload); ctx.failed.connect(self.reload); self.reload()

    def reload(self):
        busy, active = bool(self.job or self.ctx.loading), (self.ctx.cfg.get("model"), self.ctx.cfg.get("runtime"))  # one engine job at a time
        for key, (badge, files, rt, dl, use) in self.cards.items():
            have = {r: os.path.exists(model_path(key, r)) for r in RUNTIMES}
            pill(badge, *(("active · " + active[1], "#16a34a") if key == active[0] else ("downloaded", "#2563eb") if any(have.values()) else ("not downloaded", "#64748b")))
            files.setText("Files on this PC:   " + "   ·   ".join("%s %s" % (RUNTIMES[r], "✔" if have[r] else "✖") for r in RUNTIMES))
            dl.setVisible(not have[rt.currentData()]); dl.setEnabled(not busy); use.setEnabled(not busy and (key, rt.currentData()) != active)

    def start(self, fn):
        key = self.sender().key; job = self.job = (key, self.cards[key][2].currentData())
        self.task = Worker(lambda report: fn(*job, report), self.finished, self.failed, self.note.setText); self.reload()

    def download(self): self.start(lambda key, runtime, report: ensure_model(key, report, runtime))

    def use(self):
        live = self.ctx.live
        if live.running and not confirm(self, "Switch model", "Monitoring is running. Stop it and switch the model?"): return
        if live.running: live.toggle()
        ctx = self.ctx; ctx.loading = True; self.start(lambda key, runtime, report: load_engine(ctx.cfg, ctx.db, key, report, ctx.engine, runtime))

    def finished(self, engine):  # engine: switched (a FaceEngine) or just downloaded (a path)
        (key, runtime), self.job, self.ctx.loading = self.job, None, False; name = "%s (%s)" % (MODELS[key]["name"], RUNTIMES[runtime])
        if isinstance(engine, str): self.note.setText("✔  %s downloaded." % name)
        else:
            self.ctx.cfg.set("model", key); self.ctx.cfg.set("runtime", runtime); self.ctx.cfg.save(); self.ctx.engine = engine
            self.note.setText("✔  Now using %s." % name); self.ctx.refresh(); self.ctx.ready.emit()
        self.reload()

    def failed(self, msg):
        self.job, self.ctx.loading = None, False; self.note.setText("✖  " + msg); self.reload(); QMessageBox.critical(self, "Models", msg)


SETTINGS = [
    ("Recognition (threshold and gates: per model)", [("profile.threshold", "Match threshold (cosine)", "float", (0.1, 0.95, 0.01, 2)),
                     ("recognition.margin", "Margin over 2nd best", "float", (0, 0.3, 0.01, 2)), ("recognition.top_k", "Top-k samples per person", "int", (1, 10)),
                     ("tracking.votes", "Votes needed to confirm", "int", (1, 15)), ("tracking.window", "Vote window (frames)", "int", (1, 30)),
                     ("profile.gate", "Track appearance gate", "float", (0.1, 0.95, 0.01, 2))]),
    ("Attendance rules", [("attendance.work_start", "Work starts", "time", None), ("attendance.late_grace_min", "Late after grace (min)", "int", (0, 240)),
                          ("attendance.cooldown_sec", "Re-log cooldown (s)", "int", (5, 3600)),
                          ("attendance.checkout_gap_min", "Check-out min gap (min)", "int", (0, 720)),
                          ("attendance.save_snapshots", "Save face snapshots", "bool", None), ("attendance.save_unknown", "Save unknown faces", "bool", None),
                          ("attendance.unknown_cooldown_sec", "Unknown face cooldown (s)", "int", (1, 3600))]),
    ("Detection and quality", [("detection.min_confidence", "Min detection confidence", "float", (0.5, 1, 0.01, 2)),
                             ("detection.min_face_size", "MTCNN min face size (px)", "int", (20, 300)),
                             ("detection.max_side", "Detection image max side (px)", "int", (320, 3840)),
                             ("quality.min_face_px", "Min face size to recognize (px)", "int", (20, 400)),
                             ("quality.min_blur", "Min sharpness (Laplacian var.)", "float", (0, 500, 5, 0)),
                             ("quality.max_yaw", "Max head turn (yaw)", "float", (0.1, 1, 0.05, 2))]),
    ("Camera and performance", [("camera.transport", "RTSP transport", "choice", ["tcp", "udp"]),
                              ("camera.process_fps", "Recognition passes / s / camera", "float", (0.5, 30, 0.5, 1)),
                              ("camera.display_fps", "Display fps", "float", (1, 60, 1, 0)),
                              ("camera.reconnect_sec", "Reconnect delay (s)", "float", (0.5, 60, 0.5, 1)),
                              ("torch_threads", "CPU threads, 0 = half the cores (restart)", "int", (0, 128))]),
    ("Enrollment and security", [("enrollment.samples", "Samples per person", "int", (3, 50)),
                               ("enrollment.max_sim", "Max similarity between samples", "float", (0.8, 0.999, 0.005, 3)),
                               ("profile.min_same", "Min similarity to same person", "float", (0.1, 0.95, 0.01, 2)),
                               ("admin.require_login", "Require admin login", "bool", None)])]


class SettingsTab(QWidget):
    def __init__(self, ctx):
        super().__init__(); self.ctx, self.w, host = ctx, {}, QWidget(objectName="page"); grid = QGridLayout(host); grid.setSpacing(16)
        for i, (title, fields) in enumerate(SETTINGS):
            g = QGroupBox(title); f = QFormLayout(g); f.setVerticalSpacing(10); f.setHorizontalSpacing(16); grid.addWidget(g, i // 2, i % 2)
            for key, text, kind, extra in fields: self.w[key] = make(kind, extra); f.addRow(text, self.w[key])
        grid.setRowStretch(len(SETTINGS) // 2 + 1, 1)
        sc = QScrollArea(widgetResizable=True); sc.setWidget(host)
        lay(QVBoxLayout, sc, 1, lay(QHBoxLayout, ("Save settings", self.save, "primary"), ("Revert", self.load),
            label("CPU threads apply after a restart, tracking after monitoring restarts.", "muted"), None,
            ("Change admin password", lambda: set_password(self, ctx.cfg)), spacing=8), parent=self, margins=0, spacing=12)
        ctx.ready.connect(self.load); self.load()  # model switched: show its thresholds

    def load(self):
        for k, w in self.w.items(): setv(w, self.ctx.cfg.get(k))

    def save(self):
        for k, w in self.w.items(): self.ctx.cfg.set(k, getv(w))
        self.ctx.cfg.set("tracking.window", max(self.ctx.cfg.get("tracking.window"), self.ctx.cfg.get("tracking.votes")))
        self.ctx.cfg.save(); self.load(); QMessageBox.information(self, "Settings", "Settings saved.")


class Main(QMainWindow):
    PAGES = [("◉   Live monitor", LiveTab), ("☺   Employees", EmployeesTab), ("▤   Attendance", AttendanceTab),
             ("◎   Cameras", CamerasTab), ("◈   Models", ModelsTab), ("⚙   Settings", SettingsTab)]

    def __init__(self, ctx):
        super().__init__(); self.ctx = ctx; self.setWindowTitle("FaceAttend - Face Recognition Attendance"); self.resize(1480, 900)
        apply_theme()
        side, self.nav, self.stack = QFrame(objectName="sidebar"), QListWidget(objectName="nav"), QStackedWidget()
        side.setFixedWidth(240); self.nav.setCursor(Qt.PointingHandCursor)
        for name, cls in self.PAGES: self.nav.addItem(name); self.stack.addWidget(cls(ctx))
        self.live, self.engine, self.count = self.stack.widget(0), QLabel(), label("", styleSheet="color:#64748b; font-size:9pt", wordWrap=True)
        ctx.live = self.live
        pill(self.engine, "loading engine", "#f59e0b")
        lay(QVBoxLayout, label("FaceAttend", "brand"), label("Face recognition attendance", "brandSub"), label(""), self.nav, 1, self.engine, self.count,
            parent=side, margins=(16, 22, 16, 18), spacing=6)
        self.title, self.clock, content = label("", "title"), label("", "clock"), QWidget(objectName="page")
        lay(QVBoxLayout, lay(QHBoxLayout, self.title, None, self.clock), self.stack, 1, parent=content, margins=(26, 20, 26, 20), spacing=16)
        root = QWidget(); lay(QHBoxLayout, side, content, 1, parent=root, margins=0, spacing=0); self.setCentralWidget(root)
        self.nav.currentRowChanged.connect(self.go); self.nav.setCurrentRow(0)
        QTimer(self, timeout=self.tick).start(1000); self.tick()
        ctx.changed.connect(self.status); self.status(); ctx.ready.connect(self.ready); ctx.failed.connect(self.failed)

    def go(self, i): self.stack.setCurrentIndex(i); self.title.setText(self.PAGES[i][0].split(None, 1)[1])
    def tick(self): self.clock.setText(datetime.now().strftime("%A, %d %B %Y   %H:%M:%S"))
    def ready(self): pill(self.engine, "engine ready · cpu", "#22c55e"); self.status()
    def status(self):
        c = self.ctx.cfg; self.count.setText("%s · %s<br>%d people  ·  %d face samples" % (MODELS[c.get("model")]["name"], c.get("runtime").upper(),
                                                                                          self.ctx.gallery.persons, self.ctx.gallery.samples))

    def failed(self, m):
        pill(self.engine, "engine failed", "#ef4444")
        QMessageBox.critical(self, "Face engine", "Could not load the face engine:\n%s\n\nThe first start needs internet for the model weights." % m)

    def closeEvent(self, e):
        if self.live.running and not confirm(self, "Exit", "Monitoring is running. Stop it and exit?"): return e.ignore()
        if self.live.running: self.live.toggle()
        self.ctx.cams.stop_all(); self.ctx.db.close()