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
 
 
 
 
af38f77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e575ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aedfc98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af38f77
 
 
 
7aff23a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
"""

Explorer Consultant Bot β€” FastAPI entry point.



Run locally:

    cd FastAPI

    uvicorn main:app --reload --port 8000



All routes:

    GET  /                         β†’ redirect to /home or /login

    GET  /login                    β†’ login form

    POST /login                    β†’ validate, set cookie, redirect

    POST /setup-password           β†’ first-time password creation

    GET  /logout                   β†’ clear session + cookie

    GET  /home                     β†’ authenticated home

    GET  /consultants              β†’ objection analyzer page

    GET  /api/services             β†’ JSON: services for a given group

    GET  /api/type-cluster-map     β†’ JSON: objection type β†’ cluster list

    POST /api/predict              β†’ JSON: run DistilBERT prediction

    POST /api/correction           β†’ save staff correction

    GET  /browse                   β†’ response browser

    POST /browse/edit              β†’ save response edit to database
    POST /browse/delete            β†’ delete service/type/cluster from Browse
    GET  /browse/export.csv        β†’ CSV download of Browse responses
    GET  /analytics                β†’ analytics dashboard

    GET  /api/analytics-data       β†’ JSON: interactions + stats for charts

    POST /analytics/delete         β†’ admin: delete interactions

    GET  /admin                    β†’ admin panel (3 tabs)

    POST /admin/users/add          β†’ add new user

    POST /admin/users/update       β†’ update user role / name / status / password

    POST /admin/corrections/delete β†’ delete a correction row

    GET  /admin/export/users       β†’ CSV download of all users

"""

from __future__ import annotations

import csv
import io
import json
import os
import re
import sys
import threading
from collections import Counter
from contextlib import asynccontextmanager
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from typing import Optional

import pandas as pd
from fastapi import Depends, FastAPI, Form, HTTPException, Request, Response
from fastapi.responses import (
    HTMLResponse,
    JSONResponse,
    RedirectResponse,
    StreamingResponse,
)
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel

from core import auth
from core import database as db

# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------

BASE_DIR      = Path(__file__).parent
REPO_DIR      = BASE_DIR.parent
RESPONSES_CSV = REPO_DIR / "data" / "responses.csv"
SERVICES_CSV  = REPO_DIR / "Webapp" / "Services.csv"

# ---------------------------------------------------------------------------
# Group display labels
# ---------------------------------------------------------------------------

GROUP_DISPLAY  = {"VISA - KH": "VISA - KHMER", "VISA-FOR": "VISA - FOREIGNER"}
GROUP_INTERNAL = {v: k for k, v in GROUP_DISPLAY.items()}
GROUP_LABELS   = list(GROUP_DISPLAY.values())   # ["VISA - KHMER", "VISA - FOREIGNER"]
APP_TZ         = timezone(timedelta(hours=7))

# ---------------------------------------------------------------------------
# Helpers: load data from CSV files (called at startup + after edits)
# ---------------------------------------------------------------------------


def _load_services() -> dict[str, list[str]]:
    """Return {internal_group: [service_code, ...]} from Services.csv."""
    services: dict[str, list[str]] = {}
    try:
        with open(SERVICES_CSV, encoding="utf-8") as f:
            for line in f:
                line = line.strip().rstrip(",")
                if not line:
                    continue
                parts = line.split(",", 1)
                if len(parts) == 2:
                    group = parts[0].strip()
                    code  = parts[1].strip()
                    if code:
                        services.setdefault(group, []).append(code)
    except Exception:
        pass
    return services


RESPONSE_COLUMNS = (
    "service", "customer_group", "destination", "cluster", "objection_type",
    "severity", "video_id",
    "perfect_response", "perfect_response_km",
    "solution", "solution_km",
    "follow_up_question", "follow_up_question_km",
)


def _normalise_group(group: str) -> str:
    group = (group or "").strip()
    if group.upper().replace(" ", "") in {"VISA-FOR", "VISA-FOREIGNER"} or group.upper() == "VISA - FOR":
        return "VISA-FOR"
    return group


def _load_response_seed_rows() -> list[dict]:
    """Read responses.csv as an additive matrix seed for the DB table."""
    if not RESPONSES_CSV.exists():
        return []
    try:
        df = pd.read_csv(RESPONSES_CSV, dtype=str, keep_default_na=False)
    except Exception:
        return []
    for col in RESPONSE_COLUMNS:
        if col not in df.columns:
            df[col] = ""
        df[col] = df[col].fillna("").astype(str).str.strip()
    df["customer_group"] = df["customer_group"].map(_normalise_group)
    df["destination"] = df["destination"].str.upper()
    df = df[
        (df["service"].str.strip() != "")
        & (df["customer_group"].str.strip() != "")
        & (df["cluster"].str.strip() != "")
        & (df["objection_type"].str.strip() != "")
    ].copy()
    df = df.drop_duplicates(["service", "customer_group", "destination", "objection_type", "cluster"], keep="first")
    return df[list(RESPONSE_COLUMNS)].to_dict(orient="records")


def _load_responses() -> pd.DataFrame:
    """Load database-backed Browse responses, seeding missing matrix rows from CSV."""
    try:
        db.seed_browse_responses(_load_response_seed_rows(), updated_by="csv-seed")
        rows = db.get_browse_responses()
        df = pd.DataFrame(rows)
        for col in ("id", *RESPONSE_COLUMNS):
            if col not in df.columns:
                df[col] = ""
            df[col] = df[col].fillna("").astype(str).str.strip()
        return df
    except Exception:
        return pd.DataFrame()


def _load_active_services() -> dict[str, list[str]]:
    """Return services that still have active DB response rows."""
    df = _load_responses()
    services: dict[str, list[str]] = {}
    if not df.empty and {"customer_group", "service"}.issubset(df.columns):
        for group, group_df in df.groupby("customer_group"):
            codes = sorted(
                {
                    str(service).strip()
                    for service in group_df["service"].tolist()
                    if str(service).strip()
                }
            )
            if codes:
                services[str(group).strip()] = codes
    return services or _load_services()


def _load_type_cluster_map() -> dict[str, list[str]]:
    """Return {objection_type: [cluster, ...]} from responses.csv."""
    try:
        df = _load_responses()
        result: dict[str, set] = {}
        for _, row in df.iterrows():
            t = str(row.get("objection_type", "")).strip()
            c = str(row.get("cluster", "")).strip()
            if t and c and t != "nan" and c != "nan":
                result.setdefault(t, set()).add(c)
        return {t: sorted(clusters) for t, clusters in sorted(result.items())}
    except Exception:
        return {}


def _extract_destination(service_code: str) -> str:
    m = re.match(r"VISA\s*[-]\s*([A-Z]+)\s*[|]?", service_code.strip())
    return m.group(1) if m else ""


def _service_has_objection(
    service: str,
    customer_group: str,
    destination: str,
    objection_type: str,
    cluster: str,
) -> Optional[bool]:
    """Return whether a predicted type/cluster is valid for the selected service.

    None means there is not enough service context to make the decision.
    """
    service = (service or "").strip()
    objection_type = (objection_type or "").strip().lower()
    cluster = (cluster or "").strip().lower()
    if not service or not objection_type or not cluster:
        return None

    df = _load_responses()
    if df.empty:
        return None

    work = df.copy()
    for col in ("service", "customer_group", "destination", "objection_type", "cluster"):
        if col not in work.columns:
            work[col] = ""
        work[col] = work[col].fillna("").astype(str).str.strip()

    pair_exists_anywhere = (
        (work["objection_type"].str.lower() == objection_type)
        & (work["cluster"].str.lower() == cluster)
    ).any()
    if not pair_exists_anywhere:
        return None

    exact = (
        (work["service"].str.lower() == service.lower())
        & (work["objection_type"].str.lower() == objection_type)
        & (work["cluster"].str.lower() == cluster)
    )
    if customer_group:
        exact &= work["customer_group"].str.lower() == customer_group.strip().lower()
    if destination:
        exact &= (
            (work["destination"].str.upper() == destination.strip().upper())
            | (work["destination"].str.strip() == "")
        )
    return bool(exact.any())


_OBJECTION_SIGNAL_RE = re.compile(
    r"\b("
    r"do i need|need|required|require|missing|don't have|do not have|cannot prepare|can't prepare|"
    r"expensive|price|cost|fee|cheap|discount|refund|"
    r"slow|delay|too long|how long|fast|urgent|processing|waiting|"
    r"reject|rejected|rejection|refuse|refused|blacklist|guarantee|approve|approval|risk|"
    r"document|passport|bank|statement|salary|employment|letter|leave|patent|"
    r"certificate|marriage|minor|birth|sponsor|deposit|work permit|"
    r"location|office|far|map|come|visit|"
    r"trust|scam|fake|forge|forgery|competitor|"
    r"another agency|other agency|other company|other business|other firm|"
    r"their staff|their service|not like you|not like your side|your side|"
    r"answer all my questions|reply all my questions|respond all my questions|"
    r"good at explaining|explain more detail|don't know much|don't understand much|"
    r"travel history|extension"
    r")\b",
    re.IGNORECASE,
)

_NON_OBJECTION_RE = re.compile(
    r"^\s*(hi|hello|hey|thanks|thank you|ok|okay|yes|no|good morning|good afternoon|"
    r"good evening|test|testing|asdf|qwerty|what is your name|who are you)\s*[.!?]*\s*$",
    re.IGNORECASE,
)


def _contains_customer_objection(quote: str) -> bool:
    """Return True when text looks relevant to a customer visa objection."""
    cleaned = re.sub(r"\s+", " ", quote or "").strip()
    if len(cleaned) < 8:
        return False
    if _NON_OBJECTION_RE.match(cleaned):
        return False
    return bool(_OBJECTION_SIGNAL_RE.search(cleaned))


def _parse_db_timestamp(value: str) -> Optional[datetime]:
    try:
        dt = datetime.strptime(str(value), "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)
        return dt.astimezone(APP_TZ)
    except Exception:
        return None


def _percent_delta(current: int | float, previous: int | float) -> int:
    if previous == 0:
        return 0 if current == 0 else 100
    return int(round(((current - previous) / previous) * 100))


def _home_dashboard(user: dict) -> dict:
    now = datetime.now(APP_TZ)
    start_today = now.replace(hour=0, minute=0, second=0, microsecond=0)
    start_yesterday = start_today - timedelta(days=1)
    start_week = start_today - timedelta(days=start_today.weekday())
    start_prev_week = start_week - timedelta(days=7)
    one_hour_ago = now - timedelta(hours=1)

    interactions = db.get_interactions(1000)
    enriched = []
    for row in interactions:
        ts = _parse_db_timestamp(row.get("timestamp", ""))
        if not ts:
            continue
        item = dict(row)
        item["_dt"] = ts
        enriched.append(item)

    today_count = sum(1 for r in enriched if r["_dt"] >= start_today)
    yesterday_count = sum(1 for r in enriched if start_yesterday <= r["_dt"] < start_today)
    week_count = sum(1 for r in enriched if r["_dt"] >= start_week)
    prev_week_count = sum(1 for r in enriched if start_prev_week <= r["_dt"] < start_week)
    last_hour_count = sum(1 for r in enriched if r["_dt"] >= one_hour_ago)

    matched = sum(1 for r in enriched if r.get("response_found"))
    match_rate = int(round((matched / len(enriched)) * 100)) if enriched else 0

    users = db.get_all_users()
    active_staff = 0
    for staff in users:
        last_login = _parse_db_timestamp(staff.get("last_login", "") or "")
        if last_login and last_login >= start_today:
            active_staff += 1

    latest = []
    for row in enriched[:5]:
        latest.append({
            "time": row["_dt"].strftime("%H:%M"),
            "staff": row.get("user_name") or (row.get("user_email", "Staff").split("@")[0]),
            "quote": row.get("quote", ""),
            "type": row.get("objection_type") or "Unclassified",
            "cluster": row.get("cluster") or "No cluster",
            "severity": row.get("severity") or "Low",
        })

    first_name = (user.get("name") or user.get("email") or "there").split()[0]
    date_label = now.strftime("%A, %B %d").replace(" 0", " ")
    hour_word = "objection" if last_hour_count == 1 else "objections"

    return {
        "first_name": first_name,
        "date_label": date_label,
        "last_hour_count": last_hour_count,
        "last_hour_word": hour_word,
        "stats": [
            {"label": "Analyses today", "value": today_count, "delta": _percent_delta(today_count, yesterday_count), "hint": "vs. yesterday", "tone": "gold", "spark": "10,26 45,20 80,32 115,18 150,14 185,24 220,10 255,4 290,12 325,2"},
            {"label": "This week", "value": week_count, "delta": _percent_delta(week_count, prev_week_count), "hint": "vs. last week", "tone": "gold", "spark": "10,26 62,24 114,22 166,19 218,16 270,12 325,8"},
            {"label": "Match rate", "value": f"{match_rate}%", "delta": 0, "hint": "responses found", "tone": "green", "spark": "10,9 62,9 114,10 166,10 218,9 270,8 325,8"},
            {"label": "Active staff", "value": active_staff, "delta": 0, "hint": "signed in today", "tone": "blue", "spark": "10,28 62,22 114,16 166,19 218,14 270,17 325,17"},
        ],
        "latest": latest,
    }


# ---------------------------------------------------------------------------
# Module-level caches (populated at startup, refreshed after edits)
# ---------------------------------------------------------------------------

_SERVICES_MAP:     dict[str, list[str]] = {}
_TYPE_CLUSTER_MAP: dict[str, list[str]] = {}
_PREDICTOR = None          # lazy-loaded ObjectionPredictor


def _get_predictor():
    global _PREDICTOR
    if _PREDICTOR is None:
        from core.predictor import ObjectionPredictor
        _PREDICTOR = ObjectionPredictor()
    return _PREDICTOR


def _warm_predictor() -> None:
    """Load the ML models after startup so the first user request is faster."""
    try:
        _get_predictor()
        print("[ML] Predictor loaded.", flush=True)
    except Exception as e:
        print(f"[WARNING] Predictor warmup failed: {e}", file=sys.stderr, flush=True)


# ---------------------------------------------------------------------------
# App lifespan
# ---------------------------------------------------------------------------


@asynccontextmanager
async def lifespan(app: FastAPI):
    global _SERVICES_MAP, _TYPE_CLUSTER_MAP
    # ── Startup ──────────────────────────────────────────────────────────────
    # init_db() restores explorer.db from HF Hub (if HF_DB_REPO is set),
    # bootstraps the schema, seeds the admin row, and starts the background
    # sync worker thread (all idempotent / no-ops when env vars are absent).
    db.init_db()
    db.seed_browse_responses(_load_response_seed_rows(), updated_by="csv-seed")
    _SERVICES_MAP     = _load_active_services()
    _TYPE_CLUSTER_MAP = _load_type_cluster_map()
    _ensure_models()
    threading.Thread(target=_warm_predictor, daemon=True, name="predictor-warmup").start()
    yield
    # ── Shutdown ─────────────────────────────────────────────────────────────
    # Blocking final upload β€” ensures no data is lost when HF Spaces tears
    # down the container on restart.  Safe to call even if HF_DB_REPO is unset.
    db._final_push()


def _ensure_models() -> None:
    """Download ML models from HF Hub into /tmp/hf_artifacts if not local."""
    repo_artifacts = REPO_DIR / "artifacts"
    notebook_artifacts = REPO_DIR / "notebooks" / "artifacts"
    for artifacts_dir in (repo_artifacts, notebook_artifacts):
        if (artifacts_dir / "final_model.pkl").exists() or (artifacts_dir / "distilbert_stage1").exists():
            os.environ["ARTIFACTS_DIR"] = str(artifacts_dir)
            return

    local_dir = Path("/tmp/hf_artifacts")
    if (local_dir / "final_model.pkl").exists() or (local_dir / "distilbert_stage1").exists():
        os.environ["ARTIFACTS_DIR"] = str(local_dir)
        return

    hf_repo  = os.environ.get("HF_REPO_ID", "Sakda101/explorer-consultant-models")
    hf_token = os.environ.get("HF_TOKEN", "") or None
    try:
        from huggingface_hub import snapshot_download
        import shutil
        snapshot_download(
            repo_id=hf_repo, repo_type="model", token=hf_token,
            local_dir=str(local_dir),
            ignore_patterns=["*.gitattributes", ".gitattributes"],
        )
        nested = local_dir / "artifacts"
        if nested.exists() and ((nested / "final_model.pkl").exists() or (nested / "distilbert_stage1").exists()):
            for item in nested.iterdir():
                shutil.move(str(item), str(local_dir))
            nested.rmdir()
    except Exception as e:
        print(f"[WARNING] Model download failed: {e}", file=sys.stderr)
    os.environ["ARTIFACTS_DIR"] = str(local_dir)


# ---------------------------------------------------------------------------
# App + static files
# ---------------------------------------------------------------------------

app = FastAPI(title="Explorer Consultant Bot", lifespan=lifespan)
app.mount("/static", StaticFiles(directory=str(BASE_DIR / "static")), name="static")

_assets_dir = REPO_DIR / "Webapp" / "assets"
if _assets_dir.exists():
    app.mount("/assets", StaticFiles(directory=str(_assets_dir)), name="assets")

templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))


def _render(

    request: Request,

    template_name: str,

    context: Optional[dict] = None,

    status_code: int = 200,

):
    """Render templates across Starlette's old and new TemplateResponse APIs."""
    ctx = {"request": request}
    if context:
        ctx.update(context)
    try:
        return templates.TemplateResponse(request, template_name, ctx, status_code=status_code)
    except TypeError:
        return templates.TemplateResponse(template_name, ctx, status_code=status_code)


@app.exception_handler(auth._NotAuthenticated)
async def not_authenticated_handler(request: Request, exc: auth._NotAuthenticated):
    return RedirectResponse(url="/login", status_code=303)


# ---------------------------------------------------------------------------
# ── Auth routes ──────────────────────────────────────────────────────────────
# ---------------------------------------------------------------------------


@app.get("/", response_class=HTMLResponse)
async def root(request: Request):
    return RedirectResponse(
        url="/home" if auth.get_current_user(request) else "/login",
        status_code=303,
    )


@app.get("/login", response_class=HTMLResponse)
async def login_page(request: Request):
    if auth.get_current_user(request):
        return RedirectResponse(url="/home", status_code=303)
    return _render(request, "login.html")


@app.post("/login")
async def login_submit(

    request: Request,

    response: Response,

    email:    str = Form(...),

    password: str = Form(...),

):
    user = auth.attempt_login(email, password)
    if user is None:
        return _render(
            request,
            "login.html",
            {"error": "Incorrect email or password, or your account is inactive."},
            status_code=401,
        )
    db.update_last_login(user["email"])
    db.log_activity(user["email"], user["name"], "login", page="login")
    token = auth.create_session(user)
    redirect = RedirectResponse(url="/home", status_code=303)
    auth.set_session_cookie(redirect, token)
    return redirect


@app.post("/setup-password")
async def setup_password(

    request:  Request,

    email:    str = Form(...),

    password: str = Form(...),

    confirm:  str = Form(...),

):
    """First-time password creation β€” only works when password_hash is NULL."""
    email = email.strip().lower()
    ctx   = {}

    if not email or not password:
        return _render(
            request, "login.html", {**ctx, "error": "Please fill in all fields."}, status_code=400
        )
    if password != confirm:
        return _render(
            request, "login.html", {**ctx, "error": "Passwords do not match."}, status_code=400
        )
    if len(password) < 6:
        return _render(
            request, "login.html", {**ctx, "error": "Password must be at least 6 characters."}, status_code=400
        )

    user = db.get_user(email)
    if user is None or not user.get("active"):
        return _render(
            request, "login.html", {**ctx, "error": "Email not found or account is inactive."}, status_code=400
        )
    if user.get("password_hash"):
        return _render(
            request,
            "login.html",
            {**ctx, "error": "This account already has a password β€” use the Sign In form."},
            status_code=400,
        )

    auth.set_user_password(email, password)
    return _render(
        request,
        "login.html",
        {**ctx, "success": "βœ… Password created! You can now sign in above."},
    )


@app.get("/logout")
async def logout(request: Request):
    token = request.cookies.get(auth.COOKIE_NAME)
    if token:
        db.delete_session(token)
    redirect = RedirectResponse(url="/login", status_code=303)
    auth.clear_session_cookie(redirect)
    return redirect


# ---------------------------------------------------------------------------
# ── Home ─────────────────────────────────────────────────────────────────────
# ---------------------------------------------------------------------------


@app.get("/home", response_class=HTMLResponse)
async def home_page(request: Request, user: dict = Depends(auth.require_auth)):
    return _render(request, "home.html", {"user": user, "home": _home_dashboard(user)})


# ---------------------------------------------------------------------------
# ── Consultants ──────────────────────────────────────────────────────────────
# ---------------------------------------------------------------------------


@app.get("/consultants", response_class=HTMLResponse)
async def consultants_page(

    request: Request,

    user: dict = Depends(auth.require_role("consultants")),

):
    return _render(
        request,
        "consultants.html",
        {
            "user":             user,
            "services_json":    json.dumps(_SERVICES_MAP),
            "type_cluster_json": json.dumps(_TYPE_CLUSTER_MAP),
            "group_labels":     GROUP_LABELS,
        },
    )


@app.get("/api/services")
async def api_services(group: str = ""):
    """Return service list for a given display-label group."""
    internal = GROUP_INTERNAL.get(group, group)
    return JSONResponse(_SERVICES_MAP.get(internal, []))


@app.get("/api/type-cluster-map")
async def api_type_cluster_map():
    return JSONResponse(_TYPE_CLUSTER_MAP)


class PredictRequest(BaseModel):
    quote:          str
    customer_group: str = ""
    service:        str = ""
    customer_name: str = ""
    objection_status: str = ""
    first_contact_date: str = ""
    objection_date: str = ""
    main_contact_platform: str = ""
    ad_source: str = ""
    lead_quality: str = ""


_OBJECTION_STATUSES = {"Solved", "Unsolved"}
_CONTACT_PLATFORMS = {
    "Explorer Webapp",
    "Explorer by SL",
    "Explorer Travel Agency",
}
_LEAD_QUALITIES = {
    "Qualified",
    "Not Qualified",
    "Lost",
    "Converted",
    "Intake",
    "Awaiting Documents",
}


def _clean_tracking_choice(value: str, allowed: set[str], field_name: str, *, default: str = "") -> str:
    value = (value or "").strip()
    if not value:
        return default
    if value not in allowed:
        raise HTTPException(status_code=400, detail=f"Invalid {field_name}.")
    return value


def _clean_tracking_date(value: str, field_name: str) -> str:
    value = (value or "").strip()
    if not value:
        return ""
    try:
        date.fromisoformat(value)
    except ValueError:
        raise HTTPException(status_code=400, detail=f"Invalid {field_name}.")
    return value


@app.post("/api/predict")
async def api_predict(body: PredictRequest, request: Request):
    user = auth.get_current_user(request)
    if user is None:
        raise HTTPException(status_code=401, detail="Not authenticated")

    quote          = (body.quote or "").strip()
    customer_group = (body.customer_group or "").strip()
    service        = (body.service or "").strip()
    customer_name = (body.customer_name or "").strip()[:120]
    objection_status = _clean_tracking_choice(
        body.objection_status,
        _OBJECTION_STATUSES,
        "objection status",
        default="Unsolved",
    )
    first_contact_date = _clean_tracking_date(body.first_contact_date, "first contact date")
    objection_date = _clean_tracking_date(body.objection_date, "objection date")
    main_contact_platform = _clean_tracking_choice(
        body.main_contact_platform,
        _CONTACT_PLATFORMS,
        "main contact platform",
    )
    ad_source = (body.ad_source or "").strip()[:120]
    lead_quality = _clean_tracking_choice(body.lead_quality, _LEAD_QUALITIES, "lead quality")

    if not quote:
        raise HTTPException(status_code=400, detail="quote cannot be empty")

    if not _contains_customer_objection(quote):
        return JSONResponse({
            "no_objection": True,
            "quote": quote,
            "message": "This quote does not contain a customer objection.",
        })

    # Resolve display group β†’ internal key
    internal_group = GROUP_INTERNAL.get(customer_group, customer_group)
    destination    = _extract_destination(service)

    try:
        predictor = _get_predictor()
        result    = predictor.predict(quote, customer_group=internal_group, destination=destination)

        # Apply staff corrections (override type/cluster if a match is found)
        from core.corrections import apply_corrections_to_result
        result = apply_corrections_to_result(
            quote, result, predictor=predictor,
            customer_group=internal_group, destination=destination,
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Prediction failed: {e}")

    # Log the interaction
    db.log_interaction(
        user_email=user["email"],
        user_name=user["name"],
        customer_name=customer_name,
        quote=quote,
        objection_type=result.objection_type,
        cluster=result.cluster,
        customer_group=internal_group,
        destination=destination,
        service=service,
        severity=result.severity or "",
        stage1_confidence=result.objection_type_confidence,
        response_found=result.response_lookup_succeeded,
        objection_status=objection_status,
        first_contact_date=first_contact_date,
        objection_date=objection_date,
        main_contact_platform=main_contact_platform,
        ad_source=ad_source,
        lead_quality=lead_quality,
    )

    payload = result.to_dict()
    payload.update({
        "customer_name": customer_name,
        "objection_status": objection_status,
        "first_contact_date": first_contact_date,
        "objection_date": objection_date,
        "main_contact_platform": main_contact_platform,
        "ad_source": ad_source,
        "lead_quality": lead_quality,
    })
    service_objection_exists = _service_has_objection(
        service=service,
        customer_group=internal_group,
        destination=destination,
        objection_type=result.objection_type,
        cluster=result.cluster,
    )
    if service_objection_exists is False:
        payload["service_objection_exists"] = False
        payload["service_objection_message"] = "This objection does not exist for this visa service"
        payload["response_lookup_succeeded"] = False
    elif service_objection_exists is True:
        payload["service_objection_exists"] = True

    return JSONResponse(payload)


class CorrectionRequest(BaseModel):
    quote:             str
    original_type:     str
    original_cluster:  str
    corrected_type:    str
    corrected_cluster: str
    customer_group:    str = ""
    destination:       str = ""
    service:           str = ""


@app.post("/api/correction")
async def api_correction(body: CorrectionRequest, request: Request):
    user = auth.get_current_user(request)
    if user is None:
        raise HTTPException(status_code=401, detail="Not authenticated")

    from core.corrections import _normalize
    quote_norm = _normalize(body.quote)

    db.save_correction(
        user_email=user["email"],
        user_name=user["name"],
        quote=body.quote,
        quote_normalized=quote_norm,
        original_type=body.original_type,
        original_cluster=body.original_cluster,
        corrected_type=body.corrected_type,
        corrected_cluster=body.corrected_cluster,
        customer_group=body.customer_group,
        destination=body.destination,
        service=body.service,
    )
    db.log_activity(
        user["email"], user["name"], "correction",
        details=f"{body.original_type}/{body.original_cluster} β†’ {body.corrected_type}/{body.corrected_cluster}",
        page="consultants",
    )
    return JSONResponse({"ok": True})


# ---------------------------------------------------------------------------
# ── Browse ────────────────────────────────────────────────────────────────────
# ---------------------------------------------------------------------------


def _responses_as_records() -> list[dict]:
    """Load Browse responses from DB and return as JSON-safe records."""
    df = _load_responses()
    records = []
    for idx, row in df.iterrows():
        row_id = row.get("id", idx)
        try:
            row_id = int(row_id)
        except Exception:
            row_id = int(idx)
        records.append({
            "row_id":              row_id,
            "service":             row.get("service", ""),
            "customer_group":      row.get("customer_group", ""),
            "destination":         row.get("destination", ""),
            "objection_type":      row.get("objection_type", ""),
            "cluster":             row.get("cluster", ""),
            "severity":            row.get("severity", ""),
            "video_id":            row.get("video_id", ""),
            "perfect_response":    row.get("perfect_response", ""),
            "perfect_response_km": row.get("perfect_response_km", ""),
            "solution":            row.get("solution", ""),
            "solution_km":         row.get("solution_km", ""),
            "follow_up_question":  row.get("follow_up_question", ""),
            "follow_up_question_km": row.get("follow_up_question_km", ""),
        })
    return records


@app.get("/browse", response_class=HTMLResponse)
async def browse_page(

    request: Request,

    user: dict = Depends(auth.require_role("browse")),

):
    can_edit = auth.can_edit_browse_response(user)
    records = _responses_as_records()
    return _render(
        request,
        "browse.html",
        {
            "user":          user,
            "services_json": json.dumps(_SERVICES_MAP),
            "rows_json":     json.dumps(records),
            "can_edit":      can_edit,
            "group_labels":  GROUP_LABELS,
            "response_count": len(records),
        },
    )


class BrowseEditRequest(BaseModel):
    row_id:              Optional[int] = None
    service:             str = ""
    customer_group:      str = ""
    destination:         str = ""
    cluster:             str
    objection_type:      str = ""
    perfect_response:    str = ""
    perfect_response_km: str = ""
    solution:            str = ""
    solution_km:         str = ""
    follow_up_question:  str = ""
    follow_up_question_km: str = ""
    severity:            str = ""
    video_id:            str = ""


class BrowseDeleteRequest(BaseModel):
    scope: str
    value: str


class BrowseDeleteRowRequest(BaseModel):
    row_id: int


@app.post("/browse/edit")
async def browse_edit(
    body:    BrowseEditRequest,

    request: Request,

    user: dict = Depends(auth.require_role("admin_panel")),

):
    """Write edited fields to the database-backed Browse response table."""
    customer_group = body.customer_group
    destination    = body.destination
    cluster        = body.cluster
    global _TYPE_CLUSTER_MAP
    try:
        try:
            idx = db.update_browse_response(
                body.row_id,
                {
                    "service": body.service,
                    "customer_group": body.customer_group,
                    "destination": body.destination,
                    "cluster": body.cluster,
                    "objection_type": body.objection_type,
                    "perfect_response": body.perfect_response,
                    "perfect_response_km": body.perfect_response_km,
                    "solution": body.solution,
                    "solution_km": body.solution_km,
                    "follow_up_question": body.follow_up_question,
                    "follow_up_question_km": body.follow_up_question_km,
                    "severity": body.severity,
                    "video_id": body.video_id,
                },
                updated_by=user.get("email", ""),
            )
        except KeyError:
            raise HTTPException(status_code=404, detail="Row not found in database")

        # Refresh the in-memory cache so next /browse picks up the change
        _TYPE_CLUSTER_MAP = _load_type_cluster_map()
        # Reload predictor's response dataframe if it's been initialised
        if _PREDICTOR is not None:
            _PREDICTOR.reload_responses()

        db.log_activity(
            user["email"], user["name"], "edit_response",
            details=f"cluster={cluster} cg={customer_group} dest={destination}",
            page="browse",
        )

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to save edit: {e}")

    return JSONResponse({"ok": True, "row_id": int(idx)})


@app.post("/browse/delete")
async def browse_delete(
    body: BrowseDeleteRequest,
    request: Request,
    user: dict = Depends(auth.require_role("admin_panel")),
):
    """Delete a service, objection type, or cluster from the Browse matrix."""
    global _SERVICES_MAP, _TYPE_CLUSTER_MAP
    try:
        deleted = db.delete_browse_matrix_item(
            body.scope,
            body.value,
            deleted_by=user.get("email", ""),
        )
        _SERVICES_MAP = _load_active_services()
        _TYPE_CLUSTER_MAP = _load_type_cluster_map()
        if _PREDICTOR is not None:
            _PREDICTOR.reload_responses()

        db.log_activity(
            user["email"], user["name"], "delete_browse_matrix_item",
            details=f"{body.scope}={body.value}; rows={deleted}",
            page="browse",
        )
        return JSONResponse({"ok": True, "deleted": deleted})
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to delete Browse item: {e}")


@app.post("/browse/delete-row")
async def browse_delete_row(
    body: BrowseDeleteRowRequest,
    request: Request,
    user: dict = Depends(auth.require_role("admin_panel")),
):
    """Delete one service/objection/cluster row from the Browse matrix."""
    global _SERVICES_MAP, _TYPE_CLUSTER_MAP
    try:
        deleted_row = db.delete_browse_response_row(
            body.row_id,
            deleted_by=user.get("email", ""),
        )
        _SERVICES_MAP = _load_active_services()
        _TYPE_CLUSTER_MAP = _load_type_cluster_map()
        if _PREDICTOR is not None:
            _PREDICTOR.reload_responses()

        db.log_activity(
            user["email"], user["name"], "delete_browse_response",
            details=(
                f"id={body.row_id}; service={deleted_row.get('service', '')}; "
                f"type={deleted_row.get('objection_type', '')}; cluster={deleted_row.get('cluster', '')}"
            ),
            page="browse",
        )
        return JSONResponse({"ok": True, "deleted": 1, "row_id": body.row_id})
    except KeyError:
        raise HTTPException(status_code=404, detail="Row not found in database")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to delete Browse row: {e}")


@app.get("/browse/export.csv")
async def browse_export_csv(user: dict = Depends(auth.require_role("browse"))):
    """Export database-backed Browse responses as a CSV download."""
    csv_text = db.browse_responses_csv()
    filename = f"browse_responses_{datetime.now(APP_TZ).strftime('%Y%m%d_%H%M%S')}.csv"
    return StreamingResponse(
        io.StringIO(csv_text),
        media_type="text/csv; charset=utf-8",
        headers={"Content-Disposition": f'attachment; filename="{filename}"'},
    )


@app.get("/analytics", response_class=HTMLResponse)
async def analytics_page(

    request: Request,

    user: dict = Depends(auth.require_role("analytics")),

):
    return _render(
        request,
        "analytics.html",
        {
            "user":     user,
            "is_admin": user.get("role") == "admin",
        },
    )


@app.get("/api/analytics-data")
async def api_analytics_data(

    request:   Request,

    date_from: str = "",

    date_to:   str = "",

    from_date: str = "",   # alias β€” app.js uses both names

    to_date:   str = "",   # alias

):
    user = auth.get_current_user(request)
    if user is None:
        raise HTTPException(status_code=401, detail="Not authenticated")

    rows = db.get_interactions(limit=100_000)
    df   = pd.DataFrame(rows) if rows else pd.DataFrame()

    if df.empty:
        return JSONResponse({
            "rows":          [],
            "total":         0,
            "unique_users":  0,
            "active_staff":   0,
            "response_rate": 0,
            "avg_confidence": 0,
            "high_severity_count": 0,
            "most_common_type": "",
            "most_common_service": "",
            "most_common_destination": "",
            "metric_deltas":  {},
            "type_counts":   {},
            "cluster_counts": {},
            "service_counts": {},
            "destination_counts": {},
            "consultant_usage": [],
            "cluster_deltas": {},
            "weekly":        {},
            "is_admin":      user.get("role") == "admin",
        })

    df["timestamp"] = pd.to_datetime(df["timestamp"], errors="coerce")
    df_all = df.copy()

    # Date filtering β€” accept both date_from/date_to and from_date/to_date
    _from = date_from or from_date
    _to   = date_to   or to_date
    from_day = None
    to_day = None
    if _from:
        try:
            from_day = date.fromisoformat(_from)
            df = df[df["timestamp"].dt.date >= from_day]
        except ValueError:
            pass
    if _to:
        try:
            to_day = date.fromisoformat(_to)
            df = df[df["timestamp"].dt.date <= to_day]
        except ValueError:
            pass

    # Stats
    def _stats(frame: pd.DataFrame) -> dict:
        count = len(frame)
        users = int(frame["user_email"].nunique()) if "user_email" in frame else 0
        rate = (
            round(frame["response_found"].sum() / count * 100, 1)
            if count > 0 and "response_found" in frame else 0
        )
        confidence_value = 0
        if count > 0 and "stage1_confidence" in frame:
            confidence = pd.to_numeric(frame["stage1_confidence"], errors="coerce").dropna()
            if not confidence.empty:
                confidence_value = round(float(confidence.mean()), 2)
        return {
            "total": count,
            "unique_users": users,
            "response_rate": rate,
            "avg_confidence": confidence_value,
        }

    def _delta(current: float, previous: float) -> float:
        if previous == 0:
            return 0 if current == 0 else 100
        return round((current - previous) / previous * 100, 1)

    stats = _stats(df)
    total = stats["total"]
    unique_users = stats["unique_users"]
    response_rate = stats["response_rate"]
    avg_confidence = stats["avg_confidence"]

    previous_df = pd.DataFrame()
    if from_day and to_day:
        period_days = max((to_day - from_day).days + 1, 1)
        prev_to = from_day - timedelta(days=1)
        prev_from = prev_to - timedelta(days=period_days - 1)
        previous_df = df_all[
            (df_all["timestamp"].dt.date >= prev_from)
            & (df_all["timestamp"].dt.date <= prev_to)
        ]
    previous_stats = _stats(previous_df) if not previous_df.empty else {
        "total": 0,
        "unique_users": 0,
        "response_rate": 0,
        "avg_confidence": 0,
    }
    metric_deltas = {
        "total": _delta(total, previous_stats["total"]),
        "response_rate": _delta(response_rate, previous_stats["response_rate"]),
        "avg_confidence": _delta(avg_confidence, previous_stats["avg_confidence"]),
        "active_staff": _delta(unique_users, previous_stats["unique_users"]),
    }

    def _top_label(counts: dict) -> str:
        return str(next(iter(counts.keys()), ""))

    # Type distribution
    type_counts = (
        df["objection_type"].value_counts().to_dict()
        if "objection_type" in df else {}
    )

    # Top 10 clusters
    cluster_counts = {}
    if "cluster" in df:
        cluster_counts = df["cluster"].value_counts().head(10).to_dict()
    previous_cluster_counts = (
        previous_df["cluster"].value_counts().to_dict()
        if not previous_df.empty and "cluster" in previous_df else {}
    )
    cluster_deltas = {
        str(cluster): _delta(float(count), float(previous_cluster_counts.get(cluster, 0)))
        for cluster, count in cluster_counts.items()
    }

    service_counts = {}
    if "service" in df:
        service_counts = (
            df["service"]
            .fillna("")
            .astype(str)
            .str.strip()
            .replace("", pd.NA)
            .dropna()
            .value_counts()
            .head(10)
            .to_dict()
        )

    destination_counts = {}
    if "destination" in df:
        destination_counts = (
            df["destination"]
            .fillna("")
            .astype(str)
            .str.strip()
            .replace("", pd.NA)
            .dropna()
            .value_counts()
            .head(10)
            .to_dict()
        )

    high_severity_count = 0
    if "severity" in df:
        high_severity_count = int(
            df["severity"].fillna("").astype(str).str.strip().str.lower().eq("high").sum()
        )

    consultant_usage = []
    if "user_name" in df:
        user_group = df.copy()
        user_group["user_name"] = user_group["user_name"].fillna("").astype(str).str.strip().replace("", "Unknown")
        grouped = user_group.groupby("user_name")
        for name, frame in grouped:
            consultant_usage.append({
                "name": str(name),
                "count": int(len(frame)),
                "high": int(frame["severity"].fillna("").astype(str).str.strip().str.lower().eq("high").sum()) if "severity" in frame else 0,
                "response_rate": round(float(frame["response_found"].sum()) / len(frame) * 100, 1) if len(frame) and "response_found" in frame else 0,
            })
        consultant_usage = sorted(consultant_usage, key=lambda item: item["count"], reverse=True)[:10]

    # Weekly volume
    weekly_counts: dict = {}
    if not df.empty and "timestamp" in df:
        df["week"] = df["timestamp"].dt.to_period("W").dt.start_time.dt.strftime("%Y-%m-%d")
        weekly_counts = df.groupby("week").size().to_dict()

    # Row records for the table (most recent 500)
    row_records = []
    for _, r in df.sort_values("timestamp", ascending=False).head(500).iterrows():
        row_records.append({
            "id":             int(r.get("id", 0)),
            "timestamp":      str(r.get("timestamp", ""))[:16],
            "user_name":      r.get("user_name", ""),
            "customer_name":  r.get("customer_name", ""),
            "quote":          r.get("quote", ""),
            "objection_type": r.get("objection_type", ""),
            "cluster":        r.get("cluster", ""),
            "severity":       r.get("severity", ""),
            "confidence":     r.get("stage1_confidence", ""),
            "customer_group": r.get("customer_group", ""),
            "destination": r.get("destination", ""),
            "service": r.get("service", ""),
            "objection_status": r.get("objection_status", ""),
            "first_contact_date": r.get("first_contact_date", ""),
            "objection_date": r.get("objection_date", ""),
            "main_contact_platform": r.get("main_contact_platform", ""),
            "ad_source": r.get("ad_source", ""),
            "lead_quality": r.get("lead_quality", ""),
        })

    return JSONResponse({
        "rows":           row_records,
        "total":          total,
        "unique_users":   unique_users,
        "active_staff":    unique_users,
        "response_rate":  response_rate,
        "avg_confidence":  avg_confidence,
        "high_severity_count": high_severity_count,
        "most_common_type": _top_label(type_counts),
        "most_common_service": _top_label(service_counts),
        "most_common_destination": _top_label(destination_counts),
        "metric_deltas":   metric_deltas,
        "type_counts":    type_counts,
        "cluster_counts": cluster_counts,
        "service_counts": service_counts,
        "destination_counts": destination_counts,
        "consultant_usage": consultant_usage,
        "cluster_deltas": cluster_deltas,
        "weekly":         weekly_counts,
        "is_admin":       user.get("role") == "admin",
    })


class AnalyticsDeleteRequest(BaseModel):
    # id-based delete: list of int IDs
    ids:       Optional[list] = None
    # date-range delete: ISO date strings
    date_from: str = ""
    date_to:   str = ""


class AnalyticsStatusRequest(BaseModel):
    id: int
    objection_status: str


class AnalyticsLeadQualityRequest(BaseModel):
    id: int
    lead_quality: str


class AnalyticsInteractionEditRequest(BaseModel):
    id: int
    customer_name: str = ""
    quote: str = ""
    objection_status: str = "Unsolved"
    first_contact_date: str = ""
    objection_date: str = ""
    main_contact_platform: str = ""
    lead_quality: str = ""
    service: str = ""
    ad_source: str = ""
    objection_type: str = ""
    cluster: str = ""
    severity: str = ""


@app.post("/analytics/status")
async def analytics_status_update(
    body: AnalyticsStatusRequest,
    request: Request,
    user: dict = Depends(auth.require_role("analytics")),
):
    status = (body.objection_status or "").strip()
    if status not in _OBJECTION_STATUSES:
        raise HTTPException(status_code=400, detail="Invalid objection status.")
    if body.id <= 0:
        raise HTTPException(status_code=400, detail="Invalid interaction ID.")

    updated = db.update_interaction_status(body.id, status)
    if not updated:
        raise HTTPException(status_code=404, detail="Interaction not found.")
    db.log_activity(
        user["email"], user["name"], "update_objection_status",
        details=f"id={body.id} status={status}", page="analytics",
    )
    return JSONResponse({"ok": True, "id": body.id, "objection_status": status})


@app.post("/analytics/lead-quality")
async def analytics_lead_quality_update(
    body: AnalyticsLeadQualityRequest,
    request: Request,
    user: dict = Depends(auth.require_role("analytics")),
):
    lead_quality = (body.lead_quality or "").strip()
    if lead_quality not in _LEAD_QUALITIES:
        raise HTTPException(status_code=400, detail="Invalid lead quality.")
    if body.id <= 0:
        raise HTTPException(status_code=400, detail="Invalid interaction ID.")

    updated = db.update_interaction_lead_quality(body.id, lead_quality)
    if not updated:
        raise HTTPException(status_code=404, detail="Interaction not found.")
    db.log_activity(
        user["email"], user["name"], "update_lead_quality",
        details=f"id={body.id} lead_quality={lead_quality}", page="analytics",
    )
    return JSONResponse({"ok": True, "id": body.id, "lead_quality": lead_quality})


@app.post("/analytics/interaction/edit")
async def analytics_interaction_edit(
    body: AnalyticsInteractionEditRequest,
    request: Request,
    user: dict = Depends(auth.require_role("analytics")),
):
    if body.id <= 0:
        raise HTTPException(status_code=400, detail="Invalid interaction ID.")

    objection_status = _clean_tracking_choice(
        body.objection_status,
        _OBJECTION_STATUSES,
        "objection status",
        default="Unsolved",
    )
    first_contact_date = _clean_tracking_date(body.first_contact_date, "first contact date")
    objection_date = _clean_tracking_date(body.objection_date, "objection date")
    main_contact_platform = _clean_tracking_choice(
        body.main_contact_platform,
        _CONTACT_PLATFORMS,
        "main contact platform",
    )
    lead_quality = _clean_tracking_choice(body.lead_quality, _LEAD_QUALITIES, "lead quality")
    severity = (body.severity or "").strip()
    if severity and severity not in {"Low", "Medium", "High"}:
        raise HTTPException(status_code=400, detail="Invalid severity.")

    service = (body.service or "").strip()
    fields = {
        "customer_name": (body.customer_name or "").strip()[:120],
        "quote": (body.quote or "").strip(),
        "objection_status": objection_status,
        "first_contact_date": first_contact_date,
        "objection_date": objection_date,
        "main_contact_platform": main_contact_platform,
        "lead_quality": lead_quality,
        "service": service,
        "destination": _extract_destination(service),
        "ad_source": (body.ad_source or "").strip()[:120],
        "objection_type": (body.objection_type or "").strip(),
        "cluster": (body.cluster or "").strip(),
        "severity": severity,
    }
    if not fields["quote"]:
        raise HTTPException(status_code=400, detail="Exact quote is required.")

    updated = db.update_interaction_fields(body.id, fields)
    if not updated:
        raise HTTPException(status_code=404, detail="Interaction not found.")
    db.log_activity(
        user["email"], user["name"], "edit_interaction",
        details=f"id={body.id}", page="analytics",
    )
    return JSONResponse({"ok": True, "id": body.id, **fields})


@app.post("/analytics/delete")
async def analytics_delete(
    body:    AnalyticsDeleteRequest,
    request: Request,
    user: dict = Depends(auth.require_role("admin_panel")),

):
    if body.date_from and body.date_to:
        n = db.delete_interactions_by_date_range(body.date_from, body.date_to)
        db.log_activity(
            user["email"], user["name"], "delete_interactions",
            details=f"range={body.date_from}..{body.date_to} n={n}", page="analytics",
        )
        return JSONResponse({"deleted": n})
    elif body.ids:
        id_list = [int(i) for i in body.ids if isinstance(i, (int, str)) and str(i).isdigit() or isinstance(i, int)]
        if not id_list:
            raise HTTPException(status_code=400, detail="No valid IDs provided")
        n = db.delete_interactions_by_ids(id_list)
        db.log_activity(
            user["email"], user["name"], "delete_interactions",
            details=f"ids={id_list[:10]} n={n}", page="analytics",
        )
        return JSONResponse({"deleted": n})
    else:
        raise HTTPException(status_code=400, detail="Provide either ids or date_from+date_to")


# ---------------------------------------------------------------------------
# ── Admin ─────────────────────────────────────────────────────────────────────
# ---------------------------------------------------------------------------


@app.get("/admin", response_class=HTMLResponse)
async def admin_page(

    request: Request,

    user:    dict = Depends(auth.require_role("admin_panel")),

):
    users       = db.get_all_users()
    corrections = db.get_corrections(limit=500)
    for c in corrections:
        c.setdefault("created_at", c.get("timestamp", ""))
    activity = db.get_activity_log(limit=200)
    return _render(
        request,
        "admin.html",
        {"user": user, "users": users,
         "corrections": corrections, "activity": activity},
    )


@app.post("/admin/users/add")
async def admin_users_add(

    request: Request,

    user:    dict = Depends(auth.require_role("admin_panel")),

    email:   str  = Form(...),

    name:    str  = Form(...),

    role:    str  = Form(...),

):
    ok = db.add_user(email.strip().lower(), name.strip(), role)
    if ok:
        db.log_activity(user["email"], user["name"], "add_user",
                        details=f"added {email} role={role}", page="admin")
        return RedirectResponse(url="/admin?tab=users&success=User+added.", status_code=303)
    return RedirectResponse(url="/admin?tab=users&error=Email+already+exists.", status_code=303)


@app.post("/admin/users/update")
async def admin_users_update(

    request:  Request,

    user:     dict = Depends(auth.require_role("admin_panel")),

    email:    str  = Form(...),

    name:     str  = Form(""),

    role:     str  = Form(""),

    active:   str  = Form("1"),

    password: str  = Form(""),

):
    if name:
        db.update_user_name(email, name.strip())
    if role:
        db.update_user_role(email, role)
    db.update_user_active(email, int(active))
    if password:
        auth.set_user_password(email, password)
    db.log_activity(user["email"], user["name"], "edit_user",
                    details=f"updated {email}", page="admin")
    return RedirectResponse(url="/admin?tab=users&success=User+updated.", status_code=303)


@app.post("/admin/corrections/delete")
async def admin_corrections_delete(

    request:       Request,

    user:          dict = Depends(auth.require_role("admin_panel")),

    correction_id: int  = Form(...),

):
    db.delete_correction(correction_id)
    db.log_activity(user["email"], user["name"], "delete_correction",
                    details=f"correction_id={correction_id}", page="admin")
    return RedirectResponse(url="/admin?tab=corrections&success=Correction+deleted.", status_code=303)


@app.get("/admin/export/users")
async def admin_export_users(

    request: Request,

    user:    dict = Depends(auth.require_role("admin_panel")),

):
    users  = db.get_all_users()
    output = io.StringIO()
    writer = csv.DictWriter(
        output,
        fieldnames=["id", "email", "name", "role", "active", "created_at", "last_login"],
        extrasaction="ignore",
    )
    writer.writeheader()
    writer.writerows(users)
    output.seek(0)
    return StreamingResponse(
        io.BytesIO(output.getvalue().encode("utf-8")),
        media_type="text/csv",
        headers={"Content-Disposition": "attachment; filename=users.csv"},
    )