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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad2b9ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
SQLite database layer for Explorer Consultant Bot.

Tables
------
users         registered staff, their roles, and login history
interactions  every Consultants page analysis (usage analytics)
activity_log  audit trail: logins, edits, admin actions

DB file: Final Project/explorer.db  (one level above FastAPI/)

Persistence on HF Spaces
------------------------
HF Spaces has an ephemeral filesystem — explorer.db is wiped on every restart.
Set these two secrets in your HF Space to enable persistent storage via a
private HF Dataset:

  HF_DB_REPO        = Sakda101/explorer-db   (your private dataset repo)
  HF_TOKEN          = hf_xxxxxxxxxxxx         (write-access token)
  HF_SYNC_INTERVAL  = 30                      (optional, seconds between uploads)

On startup, init_db() downloads explorer.db from the dataset and launches a
single long-lived background sync worker thread.  Every write calls _push_db()
which simply sets a threading.Event.  The worker wakes, waits HF_SYNC_INTERVAL
seconds (so rapid sequential writes are coalesced into one upload), then
uploads.  A final blocking upload fires on process exit via atexit so no data
is lost when HF Spaces restarts the container.
"""

from __future__ import annotations

import atexit
import csv
import io
import os
import sqlite3
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional

# On Railway/custom: set DB_PATH env var to point to a persistent volume
# e.g. DB_PATH=/app_data/explorer.db
_default_db = Path(__file__).resolve().parents[2] / "explorer.db"
DB_PATH = Path(os.environ.get("DB_PATH", str(_default_db)))

# HF Dataset repo used for persistent DB storage on HF Spaces
_HF_DB_REPO = os.environ.get("HF_DB_REPO", "").strip()
_HF_TOKEN   = os.environ.get("HF_TOKEN", "").strip() or None

# How long the worker waits after a dirty signal before uploading (coalesces bursts)
_SYNC_INTERVAL = int(os.environ.get("HF_SYNC_INTERVAL", "30"))

# Seeded admin account — override via ADMIN_EMAIL env var when transferring ownership
_ADMIN_EMAIL = os.environ.get("ADMIN_EMAIL", "").strip().lower()

# Module-level flag: only download the DB once per server process
_db_synced_from_hub: bool = False


def _conn() -> sqlite3.Connection:
    con = sqlite3.connect(str(DB_PATH), check_same_thread=False)
    con.row_factory = sqlite3.Row
    return con


def _now() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")


# ---------------------------------------------------------------------------
# HF Hub persistence helpers  (debounced background sync worker)
# ---------------------------------------------------------------------------

# Signals that the DB has un-uploaded changes
_dirty = threading.Event()

# Ensures only one upload runs at a time (prevents interleaved writes to HF)
_upload_lock = threading.Lock()

# Guard so we only ever start one worker thread per process
_worker_started = False


def _sync_db_from_hub() -> None:
    """Download explorer.db from HF Hub dataset (runs once at startup)."""
    if not _HF_DB_REPO:
        return
    try:
        from huggingface_hub import hf_hub_download
        import shutil
        cached = hf_hub_download(
            repo_id=_HF_DB_REPO,
            filename="explorer.db",
            repo_type="dataset",
            token=_HF_TOKEN,
            force_download=True,   # always get the latest version
        )
        DB_PATH.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(cached, str(DB_PATH))
        print("[DB] Restored explorer.db from HF Hub dataset.", flush=True)
    except Exception as e:
        # File not in repo yet (first deploy) or network error — start fresh.
        print(f"[DB] Could not restore from HF Hub (first run or network issue): {e}", flush=True)


def _sync_db_to_hub() -> None:
    """Upload explorer.db to HF Hub dataset — always called while holding _upload_lock."""
    if not _HF_DB_REPO or not DB_PATH.exists():
        return
    try:
        from huggingface_hub import HfApi
        api = HfApi(token=_HF_TOKEN)
        api.upload_file(
            path_or_fileobj=str(DB_PATH),
            path_in_repo="explorer.db",
            repo_id=_HF_DB_REPO,
            repo_type="dataset",
            commit_message="auto: update explorer.db",
        )
        print("[DB] Synced explorer.db → HF Hub dataset.", flush=True)
    except Exception as e:
        print(f"[DB] HF Hub upload failed (will retry on next dirty signal): {e}", flush=True)


def _sync_worker() -> None:
    """Long-lived daemon thread: coalesces rapid writes into a single upload.

    Flow:
      1. Block on _dirty (no CPU when idle).
      2. Sleep _SYNC_INTERVAL seconds so bursts of writes are batched.
      3. Clear the flag, acquire the lock, upload.
      4. Loop back to step 1.
    """
    while True:
        _dirty.wait()                    # sleep until someone calls _push_db()
        time.sleep(_SYNC_INTERVAL)       # debounce window — let burst writes finish
        _dirty.clear()                   # consume the signal
        with _upload_lock:
            _sync_db_to_hub()


def _start_sync_worker() -> None:
    """Launch the background sync thread (idempotent — safe to call multiple times)."""
    global _worker_started
    if _worker_started or not _HF_DB_REPO:
        return
    _worker_started = True
    t = threading.Thread(target=_sync_worker, daemon=True, name="hf-db-sync")
    t.start()
    print(f"[DB] Background sync worker started (interval={_SYNC_INTERVAL}s).", flush=True)


def _final_push() -> None:
    """Blocking upload on process exit — guarantees data is saved before HF Spaces
    tears down the container.  Registered via atexit and called from FastAPI lifespan
    teardown so it fires on both graceful shutdowns and SIGTERM."""
    if not _HF_DB_REPO:
        return
    print("[DB] Shutdown: performing final sync to HF Hub…", flush=True)
    with _upload_lock:
        _sync_db_to_hub()


# Register for process-level exits (covers SIGTERM on HF Spaces)
atexit.register(_final_push)


def _push_db() -> None:
    """Signal that the DB has changed; the background worker will upload it.

    Non-blocking — returns immediately.  The actual upload is coalesced and
    deferred by _SYNC_INTERVAL seconds to avoid hammering HF Hub on rapid writes.
    """
    if _HF_DB_REPO:
        _dirty.set()


# ---------------------------------------------------------------------------
# Schema bootstrap
# ---------------------------------------------------------------------------

def _bootstrap_admin_password(con: sqlite3.Connection) -> None:
    """Set the admin password from ADMIN_PASSWORD env var if not already set.

    Called inside init_db() so it runs every time Streamlit starts.
    Safe to call repeatedly — it skips if a hash is already present.
    """
    import hashlib

    pw = os.environ.get("ADMIN_PASSWORD", "").strip()
    if not pw:
        return

    row = con.execute(
        "SELECT password_hash FROM users WHERE email = ?",
        (_ADMIN_EMAIL,),
    ).fetchone()

    if row is None or row[0]:
        return  # user doesn't exist yet, or password already set

    salt = os.urandom(16).hex()
    key = hashlib.pbkdf2_hmac(
        "sha256", pw.encode("utf-8"), salt.encode("utf-8"), 260_000
    ).hex()
    hashed = salt + ":" + key
    con.execute(
        "UPDATE users SET password_hash = ? WHERE email = ?",
        (hashed, _ADMIN_EMAIL),
    )


def init_db() -> None:
    """Create tables if they do not exist, seed the first admin, and start HF sync."""
    global _db_synced_from_hub
    if not _db_synced_from_hub:
        _sync_db_from_hub()      # restore persisted DB from HF Hub (once per process)
        _db_synced_from_hub = True

    with _conn() as con:
        con.executescript("""
            CREATE TABLE IF NOT EXISTS users (
                id         INTEGER PRIMARY KEY AUTOINCREMENT,
                email      TEXT    UNIQUE NOT NULL,
                name       TEXT    NOT NULL DEFAULT \'\',
                role       TEXT    NOT NULL DEFAULT \'staff\',
                active     INTEGER NOT NULL DEFAULT 1,
                created_at TEXT    NOT NULL,
                last_login TEXT,
                password_hash TEXT
            );

            CREATE TABLE IF NOT EXISTS interactions (
                id                INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp         TEXT    NOT NULL,
                user_email        TEXT    NOT NULL,
                user_name         TEXT    NOT NULL DEFAULT \'\',
                customer_name     TEXT    DEFAULT '',
                quote             TEXT    NOT NULL,
                objection_type    TEXT,
                cluster           TEXT,
                customer_group    TEXT,
                destination       TEXT,
                service           TEXT,
                severity          TEXT,
                stage1_confidence REAL,
                response_found    INTEGER,
                objection_status  TEXT    DEFAULT '',
                first_contact_date TEXT   DEFAULT '',
                objection_date    TEXT    DEFAULT '',
                main_contact_platform TEXT DEFAULT '',
                ad_source         TEXT    DEFAULT '',
                lead_quality      TEXT    DEFAULT ''
            );

            CREATE TABLE IF NOT EXISTS activity_log (
                id         INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp  TEXT    NOT NULL,
                user_email TEXT    NOT NULL,
                user_name  TEXT    NOT NULL DEFAULT \'\',
                action     TEXT    NOT NULL,
                details    TEXT,
                page       TEXT
            );

            CREATE TABLE IF NOT EXISTS sessions (
                token      TEXT PRIMARY KEY,
                email      TEXT NOT NULL,
                expires_at TEXT NOT NULL
            );

            CREATE TABLE IF NOT EXISTS corrections (
                id                INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp         TEXT    NOT NULL,
                user_email        TEXT    NOT NULL,
                user_name         TEXT    NOT NULL DEFAULT \'\',
                quote             TEXT    NOT NULL,
                quote_normalized  TEXT    NOT NULL,
                original_type     TEXT    NOT NULL,
                original_cluster  TEXT    NOT NULL,
                corrected_type    TEXT    NOT NULL,
                corrected_cluster TEXT    NOT NULL,
                customer_group    TEXT    DEFAULT \'\',
                destination       TEXT    DEFAULT \'\',
                service           TEXT    DEFAULT \'\',
                applied_count     INTEGER DEFAULT 0
            );

            CREATE TABLE IF NOT EXISTS browse_responses (
                id                    INTEGER PRIMARY KEY AUTOINCREMENT,
                service               TEXT NOT NULL DEFAULT '',
                customer_group        TEXT NOT NULL DEFAULT '',
                destination           TEXT NOT NULL DEFAULT '',
                objection_type        TEXT NOT NULL DEFAULT '',
                cluster               TEXT NOT NULL DEFAULT '',
                severity              TEXT NOT NULL DEFAULT '',
                solution              TEXT NOT NULL DEFAULT '',
                perfect_response      TEXT NOT NULL DEFAULT '',
                follow_up_question    TEXT NOT NULL DEFAULT '',
                video_id              TEXT NOT NULL DEFAULT '',
                perfect_response_km   TEXT NOT NULL DEFAULT '',
                solution_km           TEXT NOT NULL DEFAULT '',
                follow_up_question_km TEXT NOT NULL DEFAULT '',
                created_at            TEXT NOT NULL,
                updated_at            TEXT NOT NULL,
                updated_by            TEXT NOT NULL DEFAULT '',
                UNIQUE(service, customer_group, destination, objection_type, cluster)
            );

            CREATE TABLE IF NOT EXISTS browse_deleted_items (
                id         INTEGER PRIMARY KEY AUTOINCREMENT,
                scope      TEXT NOT NULL,
                value      TEXT NOT NULL,
                created_at TEXT NOT NULL,
                created_by TEXT NOT NULL DEFAULT '',
                UNIQUE(scope, value)
            );
        """)
        # Migration: add password_hash column if it doesn't exist yet
        try:
            con.execute("ALTER TABLE users ADD COLUMN password_hash TEXT")
        except Exception:
            pass  # Column already exists

        interaction_columns = {
            "customer_name": "TEXT DEFAULT ''",
            "objection_status": "TEXT DEFAULT ''",
            "first_contact_date": "TEXT DEFAULT ''",
            "objection_date": "TEXT DEFAULT ''",
            "main_contact_platform": "TEXT DEFAULT ''",
            "ad_source": "TEXT DEFAULT ''",
            "lead_quality": "TEXT DEFAULT ''",
        }
        existing_interaction_cols = {
            row["name"] for row in con.execute("PRAGMA table_info(interactions)").fetchall()
        }
        for column, ddl in interaction_columns.items():
            if column not in existing_interaction_cols:
                con.execute(f"ALTER TABLE interactions ADD COLUMN {column} {ddl}")

        # Seed first admin only when the table is completely empty and ADMIN_EMAIL is set
        existing = con.execute("SELECT COUNT(*) FROM users").fetchone()[0]
        if existing == 0 and _ADMIN_EMAIL:
            con.execute(
                "INSERT INTO users (email, name, role, active, created_at) VALUES (?, ?, ?, 1, ?)",
                (_ADMIN_EMAIL, "Sakda", "admin", _now()),
            )

        # Bootstrap admin password from ADMIN_PASSWORD env var (Railway).
        # Only writes if the admin row currently has no password_hash set.
        _bootstrap_admin_password(con)

    # Start the single background HF sync worker (no-op if HF_DB_REPO not set)
    _start_sync_worker()


# ---------------------------------------------------------------------------
# Browse responses
# ---------------------------------------------------------------------------

BROWSE_RESPONSE_COLUMNS = [
    "id",
    "service",
    "customer_group",
    "destination",
    "objection_type",
    "cluster",
    "severity",
    "solution",
    "perfect_response",
    "follow_up_question",
    "video_id",
    "perfect_response_km",
    "solution_km",
    "follow_up_question_km",
    "updated_at",
    "updated_by",
]

BROWSE_EDITABLE_COLUMNS = [
    "service",
    "customer_group",
    "destination",
    "objection_type",
    "cluster",
    "severity",
    "solution",
    "perfect_response",
    "follow_up_question",
    "video_id",
    "perfect_response_km",
    "solution_km",
    "follow_up_question_km",
]

BROWSE_RESPONSE_EXPORT_COLUMNS = [
    "customer_group",
    "destination",
    "cluster",
    "objection_type",
    "severity",
    "solution",
    "perfect_response",
    "follow_up_question",
    "video_id",
    "perfect_response_km",
    "solution_km",
    "follow_up_question_km",
    "service",
]


def _clean(value: object) -> str:
    return "" if value is None else str(value).strip()


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


def seed_browse_responses(rows: list[dict], *, updated_by: str = "system") -> int:
    """Insert missing Browse matrix rows without overwriting existing responses.

    This is intentionally additive. CSV files can seed or extend the matrix, but
    filled database responses remain the source of truth.
    """
    if not rows:
        return 0

    now = _now()
    inserted = 0
    with _conn() as con:
        deleted = get_browse_deleted_items(con)
        for row in rows:
            values = {
                "service": _clean(row.get("service")),
                "customer_group": _normalise_group(row.get("customer_group")),
                "destination": _clean(row.get("destination")).upper(),
                "objection_type": _clean(row.get("objection_type")),
                "cluster": _clean(row.get("cluster")),
                "severity": _clean(row.get("severity")),
                "solution": _clean(row.get("solution")),
                "perfect_response": _clean(row.get("perfect_response")),
                "follow_up_question": _clean(row.get("follow_up_question")),
                "video_id": _clean(row.get("video_id")),
                "perfect_response_km": _clean(row.get("perfect_response_km")),
                "solution_km": _clean(row.get("solution_km")),
                "follow_up_question_km": _clean(row.get("follow_up_question_km")),
                "created_at": now,
                "updated_at": now,
                "updated_by": updated_by,
            }
            if not (values["service"] and values["customer_group"] and values["cluster"] and values["objection_type"]):
                continue
            if _browse_row_is_deleted(values, deleted):
                continue
            cur = con.execute(
                """INSERT OR IGNORE INTO browse_responses
                   (service, customer_group, destination, objection_type, cluster,
                    severity, solution, perfect_response, follow_up_question, video_id,
                    perfect_response_km, solution_km, follow_up_question_km,
                    created_at, updated_at, updated_by)
                   VALUES
                   (:service, :customer_group, :destination, :objection_type, :cluster,
                    :severity, :solution, :perfect_response, :follow_up_question, :video_id,
                    :perfect_response_km, :solution_km, :follow_up_question_km,
                    :created_at, :updated_at, :updated_by)""",
                values,
            )
            inserted += cur.rowcount
    if inserted:
        _push_db()
    return inserted


def get_browse_deleted_items(con: Optional[sqlite3.Connection] = None) -> dict[str, set[str]]:
    """Return deleted matrix scopes used to keep CSV seeding from re-adding rows."""
    close_when_done = con is None
    con = con or _conn()
    try:
        rows = con.execute("SELECT scope, value FROM browse_deleted_items").fetchall()
        deleted: dict[str, set[str]] = {"service": set(), "objection_type": set(), "cluster": set(), "row": set()}
        for row in rows:
            scope = _clean(row["scope"]).lower()
            value = _clean(row["value"])
            if scope in deleted and value:
                deleted[scope].add(value.lower())
        return deleted
    finally:
        if close_when_done:
            con.close()


def _browse_row_is_deleted(row: dict, deleted: dict[str, set[str]]) -> bool:
    return (
        _browse_row_delete_key(row).lower() in deleted.get("row", set())
        or
        _clean(row.get("service")).lower() in deleted.get("service", set())
        or _clean(row.get("objection_type")).lower() in deleted.get("objection_type", set())
        or _clean(row.get("cluster")).lower() in deleted.get("cluster", set())
    )


def _browse_row_delete_key(row: dict) -> str:
    """Stable key for deleting one service/type/cluster row without deleting its peers."""
    return "|".join(
        [
            _clean(row.get("service")).lower(),
            _normalise_group(row.get("customer_group")).lower(),
            _clean(row.get("destination")).upper().lower(),
            _clean(row.get("objection_type")).lower(),
            _clean(row.get("cluster")).lower(),
        ]
    )


def get_browse_responses() -> list[dict]:
    with _conn() as con:
        rows = con.execute(
            """SELECT id, service, customer_group, destination, objection_type, cluster,
                      severity, solution, perfect_response, follow_up_question, video_id,
                      perfect_response_km, solution_km, follow_up_question_km,
                      updated_at, updated_by
               FROM browse_responses
               ORDER BY customer_group, destination, service, objection_type, cluster"""
        ).fetchall()
        return [dict(row) for row in rows]


def delete_browse_matrix_item(scope: str, value: str, *, deleted_by: str = "") -> int:
    """Delete a service, objection type, or cluster from Browse responses.

    The deletion is also recorded in browse_deleted_items so CSV seeding does
    not re-create the same matrix rows on the next app startup.
    """
    scope = _clean(scope).lower()
    value = _clean(value)
    if scope not in {"service", "objection_type", "cluster"}:
        raise ValueError("Delete scope must be service, objection_type, or cluster.")
    if not value:
        raise ValueError("Delete value is required.")

    now = _now()
    with _conn() as con:
        con.execute(
            """INSERT OR IGNORE INTO browse_deleted_items
               (scope, value, created_at, created_by)
               VALUES (?, ?, ?, ?)""",
            (scope, value, now, deleted_by),
        )
        cur = con.execute(f"DELETE FROM browse_responses WHERE {scope} = ?", (value,))
        deleted = int(cur.rowcount)
    _push_db()
    return deleted


def delete_browse_response_row(row_id: int, *, deleted_by: str = "") -> dict:
    """Delete exactly one Browse response row and prevent CSV seeding from recreating it."""
    now = _now()
    with _conn() as con:
        row = con.execute("SELECT * FROM browse_responses WHERE id = ?", (row_id,)).fetchone()
        if not row:
            raise KeyError(f"Browse response row not found: {row_id}")

        row_dict = dict(row)
        con.execute(
            """INSERT OR IGNORE INTO browse_deleted_items
               (scope, value, created_at, created_by)
               VALUES (?, ?, ?, ?)""",
            ("row", _browse_row_delete_key(row_dict), now, deleted_by),
        )
        con.execute("DELETE FROM browse_responses WHERE id = ?", (row_id,))

    _push_db()
    return row_dict


def update_browse_response(row_id: Optional[int], values: dict, *, updated_by: str = "") -> int:
    cleaned = {col: _clean(values.get(col)) for col in BROWSE_EDITABLE_COLUMNS}
    cleaned["customer_group"] = _normalise_group(cleaned["customer_group"])
    cleaned["destination"] = cleaned["destination"].upper()
    now = _now()

    with _conn() as con:
        if row_id is not None:
            existing = con.execute("SELECT id FROM browse_responses WHERE id = ?", (row_id,)).fetchone()
            if not existing:
                raise KeyError(f"Browse response row not found: {row_id}")
            assignments = ", ".join(f"{col} = :{col}" for col in BROWSE_EDITABLE_COLUMNS)
            params = dict(cleaned)
            params.update({"id": row_id, "updated_at": now, "updated_by": updated_by})
            con.execute(
                f"""UPDATE browse_responses
                    SET {assignments}, updated_at = :updated_at, updated_by = :updated_by
                    WHERE id = :id""",
                params,
            )
            saved_id = row_id
        else:
            params = dict(cleaned)
            params.update({"created_at": now, "updated_at": now, "updated_by": updated_by})
            cur = con.execute(
                """INSERT INTO browse_responses
                   (service, customer_group, destination, objection_type, cluster,
                    severity, solution, perfect_response, follow_up_question, video_id,
                    perfect_response_km, solution_km, follow_up_question_km,
                    created_at, updated_at, updated_by)
                   VALUES
                   (:service, :customer_group, :destination, :objection_type, :cluster,
                    :severity, :solution, :perfect_response, :follow_up_question, :video_id,
                    :perfect_response_km, :solution_km, :follow_up_question_km,
                    :created_at, :updated_at, :updated_by)""",
                params,
            )
            saved_id = int(cur.lastrowid)
    _push_db()
    return int(saved_id)


def browse_responses_csv() -> str:
    rows = get_browse_responses()
    buffer = io.StringIO()
    buffer.write("\ufeff")
    writer = csv.DictWriter(buffer, fieldnames=BROWSE_RESPONSE_EXPORT_COLUMNS, lineterminator="\n")
    writer.writeheader()
    for row in rows:
        writer.writerow({col: row.get(col, "") for col in BROWSE_RESPONSE_EXPORT_COLUMNS})
    return buffer.getvalue()


# ---------------------------------------------------------------------------
# Users
# ---------------------------------------------------------------------------

def get_user(email: str) -> Optional[dict]:
    with _conn() as con:
        row = con.execute("SELECT * FROM users WHERE email = ?", (email.strip().lower(),)).fetchone()
        return dict(row) if row else None


def get_all_users() -> list:
    with _conn() as con:
        rows = con.execute("SELECT * FROM users ORDER BY created_at DESC").fetchall()
        return [dict(r) for r in rows]


def add_user(email: str, name: str, role: str) -> bool:
    """Returns True on success, False if email already exists."""
    try:
        with _conn() as con:
            con.execute(
                "INSERT INTO users (email, name, role, active, created_at) VALUES (?, ?, ?, 1, ?)",
                (email.strip().lower(), name.strip(), role, _now()),
            )
        _push_db()
        return True
    except sqlite3.IntegrityError:
        return False


def update_user_role(email: str, role: str) -> None:
    with _conn() as con:
        con.execute("UPDATE users SET role = ? WHERE email = ?", (role, email))
    _push_db()


def update_user_active(email: str, active: int) -> None:
    with _conn() as con:
        con.execute("UPDATE users SET active = ? WHERE email = ?", (active, email))
    _push_db()


def update_user_name(email: str, name: str) -> None:
    with _conn() as con:
        con.execute("UPDATE users SET name = ? WHERE email = ?", (name, email))
    _push_db()


def update_last_login(email: str) -> None:
    with _conn() as con:
        con.execute("UPDATE users SET last_login = ? WHERE email = ?", (_now(), email))
    _push_db()


def delete_user(email: str) -> None:
    with _conn() as con:
        con.execute("DELETE FROM users WHERE email = ?", (email.strip().lower(),))
    _push_db()


# ---------------------------------------------------------------------------
# Interactions
# ---------------------------------------------------------------------------

def log_interaction(
    user_email: str,
    user_name: str,
    quote: str,
    customer_name: str = "",
    objection_type: str = "",
    cluster: str = "",
    customer_group: str = "",
    destination: str = "",
    service: str = "",
    severity: str = "",
    stage1_confidence: float = None,
    response_found: bool = True,
    objection_status: str = "",
    first_contact_date: str = "",
    objection_date: str = "",
    main_contact_platform: str = "",
    ad_source: str = "",
    lead_quality: str = "",
) -> None:
    with _conn() as con:
        con.execute(
            """INSERT INTO interactions
               (timestamp, user_email, user_name, customer_name, quote, objection_type, cluster,
                customer_group, destination, service, severity, stage1_confidence, response_found,
                objection_status, first_contact_date, objection_date, main_contact_platform,
                ad_source, lead_quality)
               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
            (
                _now(), user_email, user_name, customer_name, quote, objection_type, cluster,
                customer_group, destination, service, severity, stage1_confidence,
                1 if response_found else 0, objection_status, first_contact_date,
                objection_date, main_contact_platform, ad_source, lead_quality,
            ),
        )
    _push_db()  # persist to HF Hub in background


def get_interactions(limit: int = 1000) -> list:
    with _conn() as con:
        rows = con.execute(
            "SELECT * FROM interactions ORDER BY timestamp DESC LIMIT ?", (limit,)
        ).fetchall()
        return [dict(r) for r in rows]


def update_interaction_status(interaction_id: int, objection_status: str) -> bool:
    """Update the solved/unsolved status for a saved consultation record."""
    status = (objection_status or "").strip()
    if status not in {"Solved", "Unsolved"}:
        return False
    with _conn() as con:
        cur = con.execute(
            "UPDATE interactions SET objection_status = ? WHERE id = ?",
            (status, interaction_id),
        )
        changed = cur.rowcount > 0
    if changed:
        _push_db()
    return changed


def update_interaction_lead_quality(interaction_id: int, lead_quality: str) -> bool:
    """Update lead quality for a saved consultation record."""
    quality = (lead_quality or "").strip()
    allowed = {
        "Qualified",
        "Not Qualified",
        "Lost",
        "Converted",
        "Intake",
        "Awaiting Documents",
    }
    if quality not in allowed:
        return False
    with _conn() as con:
        cur = con.execute(
            "UPDATE interactions SET lead_quality = ? WHERE id = ?",
            (quality, interaction_id),
        )
        changed = cur.rowcount > 0
    if changed:
        _push_db()
    return changed


def update_interaction_fields(interaction_id: int, fields: dict) -> bool:
    """Update editable customer objection tracking fields for one interaction."""
    allowed = {
        "customer_name",
        "quote",
        "objection_type",
        "cluster",
        "severity",
        "service",
        "destination",
        "objection_status",
        "first_contact_date",
        "objection_date",
        "main_contact_platform",
        "ad_source",
        "lead_quality",
    }
    updates = {
        key: _clean(value)
        for key, value in (fields or {}).items()
        if key in allowed
    }
    if not updates:
        return False

    set_clause = ", ".join(f"{column} = ?" for column in updates)
    values = list(updates.values()) + [interaction_id]
    with _conn() as con:
        cur = con.execute(
            f"UPDATE interactions SET {set_clause} WHERE id = ?",
            values,
        )
        changed = cur.rowcount > 0
    if changed:
        _push_db()
    return changed


def delete_interactions_by_ids(ids: list) -> int:
    """Delete specific interaction rows by their id. Returns number of rows deleted."""
    if not ids:
        return 0
    placeholders = ",".join("?" * len(ids))
    with _conn() as con:
        cur = con.execute(
            f"DELETE FROM interactions WHERE id IN ({placeholders})", ids
        )
        n = cur.rowcount
    _push_db()  # persist to HF Hub in background
    return n


def delete_interactions_by_date_range(from_date: str, to_date: str) -> int:
    """Delete all interactions whose timestamp falls within [from_date, to_date].
    Dates should be ISO strings: 'YYYY-MM-DD'. Returns number of rows deleted."""
    with _conn() as con:
        cur = con.execute(
            "DELETE FROM interactions WHERE DATE(timestamp) BETWEEN ? AND ?",
            (from_date, to_date),
        )
        n = cur.rowcount
    _push_db()  # persist to HF Hub in background
    return n


# ---------------------------------------------------------------------------
# Activity log
# ---------------------------------------------------------------------------

def log_activity(
    user_email: str,
    user_name: str,
    action: str,
    details: str = "",
    page: str = "",
) -> None:
    with _conn() as con:
        con.execute(
            """INSERT INTO activity_log
               (timestamp, user_email, user_name, action, details, page)
               VALUES (?, ?, ?, ?, ?, ?)""",
            (_now(), user_email, user_name, action, details, page),
        )
    _push_db()  # persist to HF Hub in background


def get_activity_log(limit: int = 1000) -> list:
    with _conn() as con:
        rows = con.execute(
            "SELECT * FROM activity_log ORDER BY timestamp DESC LIMIT ?", (limit,)
        ).fetchall()
        return [dict(r) for r in rows]


# ---------------------------------------------------------------------------
# Corrections
# ---------------------------------------------------------------------------

def save_correction(
    user_email: str,
    user_name: str,
    quote: str,
    quote_normalized: str,
    original_type: str,
    original_cluster: str,
    corrected_type: str,
    corrected_cluster: str,
    customer_group: str = "",
    destination: str = "",
    service: str = "",
) -> int:
    """Save a staff correction. Returns the new row id."""
    with _conn() as con:
        cur = con.execute(
            """INSERT INTO corrections
               (timestamp, user_email, user_name, quote, quote_normalized,
                original_type, original_cluster, corrected_type, corrected_cluster,
                customer_group, destination, service, applied_count)
               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)""",
            (
                _now(), user_email, user_name, quote, quote_normalized,
                original_type, original_cluster, corrected_type, corrected_cluster,
                customer_group, destination, service,
            ),
        )
        rowid = cur.lastrowid
    _push_db()  # persist to HF Hub in background
    return rowid


def get_all_corrections_raw() -> list:
    """Return all corrections ordered by most recent first. Used by CorrectionStore."""
    with _conn() as con:
        rows = con.execute(
            "SELECT * FROM corrections ORDER BY timestamp DESC"
        ).fetchall()
        return [dict(r) for r in rows]


def get_corrections(limit: int = 500) -> list:
    """Return corrections for display (most recent first, capped)."""
    with _conn() as con:
        rows = con.execute(
            "SELECT * FROM corrections ORDER BY timestamp DESC LIMIT ?", (limit,)
        ).fetchall()
        return [dict(r) for r in rows]


def increment_correction_applied(correction_id: int) -> None:
    """Increment the applied_count counter for a correction row."""
    with _conn() as con:
        con.execute(
            "UPDATE corrections SET applied_count = applied_count + 1 WHERE id = ?",
            (correction_id,),
        )
    _push_db()


def delete_correction(correction_id: int) -> None:
    with _conn() as con:
        con.execute("DELETE FROM corrections WHERE id = ?", (correction_id,))
    _push_db()  # persist to HF Hub in background


# ---------------------------------------------------------------------------
# Sessions  (persistent login tokens stored per user)
# ---------------------------------------------------------------------------

def create_session(token: str, email: str, expires_at: str) -> None:
    """Store a new session token for the given user."""
    with _conn() as con:
        con.execute(
            "INSERT OR REPLACE INTO sessions (token, email, expires_at) VALUES (?, ?, ?)",
            (token, email.strip().lower(), expires_at),
        )
    _push_db()


def get_session_email(token: str) -> Optional[str]:
    """Return the email for a valid (non-expired) token, or None."""
    with _conn() as con:
        row = con.execute(
            "SELECT email, expires_at FROM sessions WHERE token = ?", (token,)
        ).fetchone()
    if not row:
        return None
    # Check expiry
    try:
        exp = datetime.strptime(row["expires_at"], "%Y-%m-%d %H:%M:%S").replace(
            tzinfo=timezone.utc
        )
        if datetime.now(timezone.utc) > exp:
            delete_session(token)
            return None
    except Exception:
        pass
    return row["email"]


def delete_session(token: str) -> None:
    """Remove a session token (logout)."""
    with _conn() as con:
        con.execute("DELETE FROM sessions WHERE token = ?", (token,))
    _push_db()


def cleanup_expired_sessions() -> None:
    """Delete all expired session rows."""
    now = _now()
    with _conn() as con:
        cur = con.execute("DELETE FROM sessions WHERE expires_at < ?", (now,))
        deleted = cur.rowcount
    if deleted:
        _push_db()


def cleanup_old_logs(days: int = 90) -> tuple[int, int]:
    """Delete activity_log and interactions rows older than `days` days.

    Returns (activity_deleted, interactions_deleted).
    Interactions are analytics data — we keep them longer by default but still
    purge very old rows to prevent unbounded DB growth.
    """
    import datetime as _dt
    cutoff = (
        _dt.datetime.now(_dt.timezone.utc) - _dt.timedelta(days=days)
    ).strftime("%Y-%m-%d %H:%M:%S")
    with _conn() as con:
        cur_a = con.execute("DELETE FROM activity_log WHERE timestamp < ?", (cutoff,))
        cur_i = con.execute("DELETE FROM interactions WHERE timestamp < ?", (cutoff,))
        a, i = cur_a.rowcount, cur_i.rowcount
    if a or i:
        _push_db()
    return a, i