File size: 40,276 Bytes
79dca2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""SQLite database layer — schema, migrations, CRUD, monitoring."""

import os
import json
import sqlite3
from datetime import datetime
from .config import settings as s
from .hub_sync import mark_dirty

DB_DIR = s.DB_DIR
DB_PATH = s.DB_PATH
SCHEMA_VERSION = 14


def get_conn():
    os.makedirs(DB_DIR, exist_ok=True)
    conn = sqlite3.connect(DB_PATH, timeout=30)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA foreign_keys = ON")
    conn.execute("PRAGMA busy_timeout = 30000")
    return conn


def _get_schema_version(conn):
    try:
        row = conn.execute("PRAGMA user_version").fetchone()
        return row[0] if row else 0
    except Exception:
        return 0


def init_db():
    conn = get_conn()
    version = _get_schema_version(conn)

    # ─── Fresh install: create all tables ───
    if version == 0:
        conn.executescript("""
            CREATE TABLE IF NOT EXISTS devices (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL UNIQUE,
                device_type TEXT NOT NULL,
                description TEXT DEFAULT '',
                sort_order INTEGER DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
            CREATE TABLE IF NOT EXISTS os_versions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                device_id INTEGER NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
                os_type TEXT NOT NULL,
                version_name TEXT NOT NULL,
                description TEXT DEFAULT '',
                sort_order INTEGER DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
            CREATE TABLE IF NOT EXISTS downloads (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                os_version_id INTEGER NOT NULL REFERENCES os_versions(id) ON DELETE CASCADE,
                file_type TEXT NOT NULL,
                title TEXT NOT NULL,
                description TEXT DEFAULT '',
                mega_link TEXT NOT NULL,
                file_size TEXT DEFAULT '',
                sort_order INTEGER DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
            CREATE TABLE IF NOT EXISTS admins (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                username TEXT UNIQUE NOT NULL,
                password_hash TEXT NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
            CREATE TABLE IF NOT EXISTS announcements (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                kind TEXT DEFAULT '公告',
                title TEXT NOT NULL,
                content TEXT NOT NULL,
                active INTEGER DEFAULT 1,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
            CREATE TABLE IF NOT EXISTS visit_logs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                ip TEXT DEFAULT '',
                user_agent TEXT DEFAULT '',
                path TEXT DEFAULT '',
                device_name TEXT DEFAULT '',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
            CREATE TABLE IF NOT EXISTS download_logs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                download_id INTEGER,
                title TEXT DEFAULT '',
                file_type TEXT DEFAULT '',
                device_name TEXT DEFAULT '',
                os_name TEXT DEFAULT '',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
            CREATE TABLE IF NOT EXISTS mega_cache (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                file_name TEXT NOT NULL UNIQUE,
                file_size INTEGER DEFAULT 0,
                mega_link TEXT,
                file_id TEXT DEFAULT '',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """)
        conn.execute(f"PRAGMA user_version = {SCHEMA_VERSION}")

    # ─── Migrations ───
    if version == 5:
        # v5 → v6: add file_id column to mega_cache
        try:
            conn.execute("ALTER TABLE mega_cache ADD COLUMN file_id TEXT DEFAULT ''")
        except Exception:
            pass  # column may already exist
        conn.execute("PRAGMA user_version = 6")

    if version <= 6:
        # v6 → v7: add problem_reports table
        conn.executescript("""
            CREATE TABLE IF NOT EXISTS problem_reports (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                sn TEXT NOT NULL,
                os_type TEXT DEFAULT '',
                problem_type TEXT NOT NULL,
                description TEXT DEFAULT '',
                os_version TEXT DEFAULT '',
                matched_filenames TEXT DEFAULT '',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                status TEXT DEFAULT 'pending',
                resolved_at TIMESTAMP,
                resolution_note TEXT DEFAULT ''
            );
        """)
        conn.execute("PRAGMA user_version = 7")

    if version <= 7:
        # v7 → v8: add sn_file_maps table
        conn.executescript("""
            CREATE TABLE IF NOT EXISTS sn_file_maps (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                sn TEXT NOT NULL UNIQUE,
                files TEXT NOT NULL DEFAULT '[]',
                note TEXT DEFAULT '',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """)
        conn.execute("PRAGMA user_version = 8")

    if version <= 8:
        # v8 → v9: add os_file_maps table
        conn.executescript("""
            CREATE TABLE IF NOT EXISTS os_file_maps (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                os_version TEXT NOT NULL UNIQUE,
                files TEXT NOT NULL DEFAULT '[]',
                note TEXT DEFAULT '',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """)
        conn.execute("PRAGMA user_version = 9")

    if version <= 9:
        # v9 → v10: add app_settings table
        conn.executescript("""
            CREATE TABLE IF NOT EXISTS app_settings (
                key TEXT PRIMARY KEY,
                value TEXT NOT NULL,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
            INSERT OR IGNORE INTO app_settings (key, value) VALUES ('map_display_mode', 'all');
        """)
        conn.execute("PRAGMA user_version = 10")

    if version <= 10:
        # v10 → v11: add mes_cache table (public MES query result cache)
        conn.executescript("""
            CREATE TABLE IF NOT EXISTS mes_cache (
                sn TEXT PRIMARY KEY,
                raw_json TEXT NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """)
        conn.execute("PRAGMA user_version = 11")

    if version <= 11:
        # v11 -> v12: add mes_query_logs table (MES query monitoring)
        conn.executescript("""
            CREATE TABLE IF NOT EXISTS mes_query_logs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                sn TEXT NOT NULL,
                cached INTEGER NOT NULL DEFAULT 0,
                status TEXT NOT NULL DEFAULT 'ok',
                duration_ms INTEGER NOT NULL DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """)
        conn.execute("PRAGMA user_version = 12")

    if version <= 12:
        # v12 -> v13: record which MES field a report refers to
        cols = {r["name"] for r in conn.execute("PRAGMA table_info(problem_reports)")}
        if "field_name" not in cols:
            conn.execute(
                "ALTER TABLE problem_reports ADD COLUMN field_name TEXT DEFAULT ''"
            )
        conn.execute("PRAGMA user_version = 13")

    if version <= 13:
        # v13 -> v14: access profiles — one row per access code, each carrying its
        # own visible-field set so a code decides what the browser is allowed to see.
        from .fields import ALL_FIELDS, DEFAULT_USER_FIELDS

        conn.executescript("""
            CREATE TABLE IF NOT EXISTS access_profiles (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                code TEXT NOT NULL UNIQUE,
                name TEXT NOT NULL DEFAULT '',
                is_admin INTEGER NOT NULL DEFAULT 0,
                visible_fields TEXT NOT NULL DEFAULT '[]',
                enabled INTEGER NOT NULL DEFAULT 1,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """)
        legacy = conn.execute(
            "SELECT value FROM app_settings WHERE key = 'mes_access_code'"
        ).fetchone()
        legacy_code = (legacy["value"] if legacy else "") or s.MES_ACCESS_CODE
        if legacy_code:
            conn.execute(
                "INSERT OR IGNORE INTO access_profiles "
                "(code, name, is_admin, visible_fields) VALUES (?, ?, 0, ?)",
                (legacy_code, "用户", json.dumps(DEFAULT_USER_FIELDS)),
            )
        conn.execute(
            "INSERT OR IGNORE INTO access_profiles "
            "(code, name, is_admin, visible_fields) VALUES (?, ?, 1, ?)",
            ("bevis", "管理员", json.dumps(ALL_FIELDS)),
        )
        conn.execute("PRAGMA user_version = 14")

    conn.commit()
    conn.close()


# ─── Device CRUD ───


def list_devices(device_type=None):
    conn = get_conn()
    if device_type:
        rows = conn.execute(
            "SELECT * FROM devices WHERE device_type=? ORDER BY sort_order, name",
            (device_type,),
        ).fetchall()
    else:
        rows = conn.execute(
            "SELECT * FROM devices ORDER BY sort_order, name"
        ).fetchall()
    conn.close()
    return [dict(r) for r in rows]


def get_device(device_id):
    conn = get_conn()
    row = conn.execute(
        "SELECT * FROM devices WHERE id=?", (device_id,)
    ).fetchone()
    conn.close()
    return dict(row) if row else None


def create_device(name, device_type, description="", sort_order=0):
    conn = get_conn()
    try:
        cur = conn.execute(
            "INSERT INTO devices (name, device_type, description, sort_order) VALUES (?,?,?,?)",
            (name, device_type, description, sort_order),
        )
        conn.commit()
        mark_dirty()
        return cur.lastrowid
    except sqlite3.IntegrityError:
        return None
    finally:
        conn.close()


def update_device(device_id, name=None, device_type=None, description=None, sort_order=None):
    conn = get_conn()
    fields, vals = [], []
    if name is not None:
        fields.append("name=?")
        vals.append(name)
    if device_type is not None:
        fields.append("device_type=?")
        vals.append(device_type)
    if description is not None:
        fields.append("description=?")
        vals.append(description)
    if sort_order is not None:
        fields.append("sort_order=?")
        vals.append(sort_order)
    if not fields:
        conn.close()
        return False
    vals.append(device_id)
    try:
        conn.execute(
            f"UPDATE devices SET {', '.join(fields)} WHERE id=?", vals
        )
        conn.commit()
        mark_dirty()
        return True
    except sqlite3.IntegrityError:
        return False
    finally:
        conn.close()


def delete_device(device_id):
    conn = get_conn()
    conn.execute("DELETE FROM devices WHERE id=?", (device_id,))
    conn.commit()
    mark_dirty()
    conn.close()


# ─── OS Version CRUD ───


def list_os_versions(device_id):
    conn = get_conn()
    rows = conn.execute(
        "SELECT * FROM os_versions WHERE device_id=? ORDER BY sort_order, version_name",
        (device_id,),
    ).fetchall()
    conn.close()
    return [dict(r) for r in rows]


def get_os_version(os_id):
    conn = get_conn()
    row = conn.execute(
        "SELECT * FROM os_versions WHERE id=?", (os_id,)
    ).fetchone()
    conn.close()
    return dict(row) if row else None


def create_os_version(device_id, os_type, version_name, description="", sort_order=0):
    conn = get_conn()
    cur = conn.execute(
        "INSERT INTO os_versions (device_id, os_type, version_name, description, sort_order) VALUES (?,?,?,?,?)",
        (device_id, os_type, version_name, description, sort_order),
    )
    conn.commit()
    mark_dirty()
    conn.close()
    return cur.lastrowid


def update_os_version(os_id, os_type=None, version_name=None, description=None, sort_order=None):
    conn = get_conn()
    fields, vals = [], []
    if os_type is not None:
        fields.append("os_type=?")
        vals.append(os_type)
    if version_name is not None:
        fields.append("version_name=?")
        vals.append(version_name)
    if description is not None:
        fields.append("description=?")
        vals.append(description)
    if sort_order is not None:
        fields.append("sort_order=?")
        vals.append(sort_order)
    if not fields:
        conn.close()
        return False
    vals.append(os_id)
    conn.execute(f"UPDATE os_versions SET {', '.join(fields)} WHERE id=?", vals)
    conn.commit()
    mark_dirty()
    conn.close()
    return True


def delete_os_version(os_id):
    conn = get_conn()
    conn.execute("DELETE FROM os_versions WHERE id=?", (os_id,))
    conn.commit()
    mark_dirty()
    conn.close()


# ─── Download CRUD ───


def list_downloads(os_version_id):
    conn = get_conn()
    rows = conn.execute(
        "SELECT * FROM downloads WHERE os_version_id=? ORDER BY sort_order, title",
        (os_version_id,),
    ).fetchall()
    conn.close()
    return [dict(r) for r in rows]


def get_download(download_id):
    conn = get_conn()
    row = conn.execute(
        "SELECT * FROM downloads WHERE id=?", (download_id,)
    ).fetchone()
    conn.close()
    return dict(row) if row else None


def create_download(os_version_id, file_type, title, mega_link, description="", file_size="", sort_order=0):
    conn = get_conn()
    cur = conn.execute(
        "INSERT INTO downloads (os_version_id, file_type, title, description, mega_link, file_size, sort_order) VALUES (?,?,?,?,?,?,?)",
        (os_version_id, file_type, title, description, mega_link, file_size, sort_order),
    )
    conn.commit()
    mark_dirty()
    conn.close()
    return cur.lastrowid


def update_download(download_id, file_type=None, title=None, description=None, mega_link=None, file_size=None, sort_order=None):
    conn = get_conn()
    fields, vals = [], []
    if file_type is not None:
        fields.append("file_type=?")
        vals.append(file_type)
    if title is not None:
        fields.append("title=?")
        vals.append(title)
    if description is not None:
        fields.append("description=?")
        vals.append(description)
    if mega_link is not None:
        fields.append("mega_link=?")
        vals.append(mega_link)
    if file_size is not None:
        fields.append("file_size=?")
        vals.append(file_size)
    if sort_order is not None:
        fields.append("sort_order=?")
        vals.append(sort_order)
    if not fields:
        conn.close()
        return False
    vals.append(download_id)
    conn.execute(f"UPDATE downloads SET {', '.join(fields)} WHERE id=?", vals)
    conn.commit()
    mark_dirty()
    conn.close()
    return True


def delete_download(download_id):
    conn = get_conn()
    conn.execute("DELETE FROM downloads WHERE id=?", (download_id,))
    conn.commit()
    mark_dirty()
    conn.close()


# ─── Admin CRUD ───


def get_admin(username):
    conn = get_conn()
    row = conn.execute(
        "SELECT * FROM admins WHERE username=?", (username,)
    ).fetchone()
    conn.close()
    return dict(row) if row else None


def create_admin(username, password_hash):
    conn = get_conn()
    try:
        conn.execute(
            "INSERT INTO admins (username, password_hash) VALUES (?,?)",
            (username, password_hash),
        )
        conn.commit()
        return True
    except sqlite3.IntegrityError:
        return False
    finally:
        conn.close()


def update_admin_password(username, password_hash):
    conn = get_conn()
    try:
        cur = conn.execute(
            "UPDATE admins SET password_hash=? WHERE username=?",
            (password_hash, username),
        )
        conn.commit()
        updated = cur.rowcount > 0
    finally:
        conn.close()
    if updated:
        mark_dirty()
    return updated


# ─── Device tree (public) ───


def get_device_tree():
    conn = get_conn()
    devices = conn.execute(
        "SELECT * FROM devices ORDER BY sort_order, name"
    ).fetchall()
    tree = []
    for d in devices:
        d = dict(d)
        os_list = conn.execute(
            "SELECT * FROM os_versions WHERE device_id=? ORDER BY sort_order, version_name",
            (d["id"],),
        ).fetchall()
        d["os_versions"] = []
        for osv in os_list:
            osv = dict(osv)
            dl_list = conn.execute(
                "SELECT * FROM downloads WHERE os_version_id=? ORDER BY sort_order, title",
                (osv["id"],),
            ).fetchall()
            osv["downloads"] = [dict(dl) for dl in dl_list]
            d["os_versions"].append(osv)
        tree.append(d)
    conn.close()
    return tree


# ─── Announcements ───


def list_announcements():
    conn = get_conn()
    rows = conn.execute(
        "SELECT * FROM announcements ORDER BY created_at DESC"
    ).fetchall()
    conn.close()
    return [dict(r) for r in rows]


def list_active_announcements():
    conn = get_conn()
    rows = conn.execute(
        "SELECT * FROM announcements WHERE active=1 ORDER BY created_at DESC"
    ).fetchall()
    conn.close()
    return [dict(r) for r in rows]


def save_announcement(id=None, kind="公告", title="", content="", active=True):
    conn = get_conn()
    now = datetime.now().isoformat()
    if id:
        conn.execute(
            "UPDATE announcements SET kind=?, title=?, content=?, active=?, updated_at=? WHERE id=?",
            (kind, title, content, 1 if active else 0, now, id),
        )
    else:
        conn.execute(
            "INSERT INTO announcements (kind, title, content, active, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",
            (kind, title, content, 1 if active else 0, now, now),
        )
        id = conn.execute("SELECT last_insert_rowid()").fetchone()[0]
    conn.commit()
    mark_dirty()
    row = conn.execute(
        "SELECT * FROM announcements WHERE id=?", (id,)
    ).fetchone()
    conn.close()
    return dict(row)


def delete_announcement(id: int):
    conn = get_conn()
    conn.execute("DELETE FROM announcements WHERE id=?", (id,))
    conn.commit()
    mark_dirty()
    conn.close()


def toggle_announcement(id: int):
    conn = get_conn()
    conn.execute(
        "UPDATE announcements SET active = CASE WHEN active=1 THEN 0 ELSE 1 END, updated_at=? WHERE id=?",
        (datetime.now().isoformat(), id),
    )
    conn.commit()
    mark_dirty()
    conn.close()


# ─── Visit / download logging ───


def log_visit(ip="", user_agent="", path="", device_name=""):
    conn = get_conn()
    conn.execute(
        "INSERT INTO visit_logs (ip, user_agent, path, device_name) VALUES (?, ?, ?, ?)",
        (ip, user_agent, path, device_name),
    )
    conn.commit()
    conn.close()


def log_download_click(download_id, title="", file_type="", device_name="", os_name=""):
    conn = get_conn()
    conn.execute(
        "INSERT INTO download_logs (download_id, title, file_type, device_name, os_name) VALUES (?, ?, ?, ?, ?)",
        (download_id, title, file_type, device_name, os_name),
    )
    conn.commit()
    conn.close()


# ─── Monitoring ───


def get_monitoring_stats():
    conn = get_conn()
    total_visits = conn.execute(
        "SELECT COUNT(*) FROM visit_logs"
    ).fetchone()[0]
    total_downloads = conn.execute(
        "SELECT COUNT(*) FROM download_logs"
    ).fetchone()[0]
    today_visits = conn.execute(
        "SELECT COUNT(*) FROM visit_logs WHERE date(created_at)=date('now')"
    ).fetchone()[0]
    today_downloads = conn.execute(
        "SELECT COUNT(*) FROM download_logs WHERE date(created_at)=date('now')"
    ).fetchone()[0]
    top_devices = conn.execute(
        "SELECT device_name, COUNT(*) as cnt FROM visit_logs WHERE device_name != '' GROUP BY device_name ORDER BY cnt DESC LIMIT 10"
    ).fetchall()
    recent_visits = conn.execute(
        "SELECT * FROM visit_logs ORDER BY created_at DESC LIMIT 50"
    ).fetchall()
    recent_downloads = conn.execute(
        "SELECT * FROM download_logs ORDER BY created_at DESC LIMIT 50"
    ).fetchall()
    daily_visits = conn.execute(
        "SELECT date(created_at) as day, COUNT(*) as cnt FROM visit_logs WHERE created_at >= datetime('now', '-30 days') GROUP BY date(created_at) ORDER BY day"
    ).fetchall()
    conn.close()
    return {
        "total_visits": total_visits,
        "total_downloads": total_downloads,
        "today_visits": today_visits,
        "today_downloads": today_downloads,
        "top_devices": [dict(r) for r in top_devices],
        "recent_visits": [dict(r) for r in recent_visits],
        "recent_downloads": [dict(r) for r in recent_downloads],
        "daily_visits": [dict(r) for r in daily_visits],
    }


# ─── MEGA Cache ───


def refresh_mega_cache(files: list[dict]):
    """Full replace of mega_cache (old approach, kept for compatibility)."""
    conn = get_conn()
    conn.execute("DELETE FROM mega_cache")
    conn.executemany(
        "INSERT INTO mega_cache (file_name, file_size, mega_link, file_id) VALUES (?, ?, ?, ?)",
        [(f["file_name"], f.get("file_size", 0), f.get("mega_link"), f.get("file_id", "")) for f in files],
    )
    conn.commit()
    conn.close()


def append_mega_cache(files: list[dict]):
    """Incremental insert (old approach, kept for compatibility)."""
    conn = get_conn()
    conn.executemany(
        "INSERT OR IGNORE INTO mega_cache (file_name, file_size, mega_link, file_id) VALUES (?, ?, ?, ?)",
        [(f["file_name"], f.get("file_size", 0), f.get("mega_link"), f.get("file_id", "")) for f in files],
    )
    conn.commit()
    conn.close()


def upsert_mega_cache(files: list[dict]):
    """Bulk upsert file_name + file_size + file_id, preserving existing mega_link.

    Uses ON CONFLICT to update file_id/file_size without touching mega_link.
    """
    conn = get_conn()
    conn.executemany(
        "INSERT INTO mega_cache (file_name, file_size, file_id) VALUES (?, ?, ?) "
        "ON CONFLICT(file_name) DO UPDATE SET file_id=excluded.file_id, file_size=excluded.file_size",
        [(f["file_name"], f.get("file_size", 0), f.get("file_id", "")) for f in files],
    )
    conn.commit()
    mark_dirty()
    conn.close()


def upsert_mega_cache_links(files: list[dict]):
    """Bulk upsert external share-link files, overwriting mega_link.

    Used for files that live outside the MEGA account tree (see mega_links.json);
    their link is already known, so it must be written rather than preserved.
    """
    conn = get_conn()
    conn.executemany(
        "INSERT INTO mega_cache (file_name, file_size, file_id, mega_link) VALUES (?, ?, ?, ?) "
        "ON CONFLICT(file_name) DO UPDATE SET file_id=excluded.file_id, "
        "file_size=excluded.file_size, mega_link=excluded.mega_link",
        [
            (f["file_name"], f.get("file_size", 0), f.get("file_id", ""), f["mega_link"])
            for f in files
        ],
    )
    conn.commit()
    mark_dirty()
    conn.close()


def update_mega_links(links: dict[str, str]):
    """Batch update mega_link WHERE file_name matches.

    links: {file_name: mega_link_url}
    """
    conn = get_conn()
    conn.executemany(
        "UPDATE mega_cache SET mega_link=? WHERE file_name=?",
        [(link, name) for name, link in links.items()],
    )
    conn.commit()
    mark_dirty()
    conn.close()


def get_exported_names() -> set[str]:
    conn = get_conn()
    rows = conn.execute("SELECT file_name FROM mega_cache").fetchall()
    conn.close()
    return {r["file_name"] for r in rows}


def get_exported_names_with_links() -> set[str]:
    conn = get_conn()
    rows = conn.execute(
        "SELECT file_name FROM mega_cache WHERE mega_link IS NOT NULL AND mega_link != ''"
    ).fetchall()
    conn.close()
    return {r["file_name"] for r in rows}


def clear_mega_cache():
    conn = get_conn()
    conn.execute("DELETE FROM mega_cache")
    conn.commit()
    mark_dirty()
    conn.close()


def search_mega_cache(keyword: str, max_results: int = 10) -> list[dict]:
    conn = get_conn()
    rows = conn.execute(
        "SELECT file_name as name, file_size as size, mega_link as link, id "
        "FROM mega_cache WHERE file_name LIKE ? ORDER BY file_name LIMIT ?",
        (f"%{keyword}%", max_results),
    ).fetchall()
    conn.close()
    return [dict(r) for r in rows]


def get_mega_cache_count() -> int:
    conn = get_conn()
    cnt = conn.execute("SELECT COUNT(*) FROM mega_cache").fetchone()[0]
    conn.close()
    return cnt


def get_mega_cache_mtime() -> float | None:
    conn = get_conn()
    row = conn.execute(
        "SELECT MAX(created_at) FROM mega_cache"
    ).fetchone()
    conn.close()
    if row and row[0]:
        return datetime.fromisoformat(row[0]).timestamp()
    return None


def get_mega_cache_stats() -> dict:
    conn = get_conn()
    total = conn.execute("SELECT COUNT(*) FROM mega_cache").fetchone()[0]
    with_links = conn.execute(
        "SELECT COUNT(*) FROM mega_cache WHERE mega_link IS NOT NULL AND mega_link != ''"
    ).fetchone()[0]
    total_size = conn.execute(
        "SELECT COALESCE(SUM(file_size), 0) FROM mega_cache"
    ).fetchone()[0]
    row = conn.execute("SELECT MAX(created_at) FROM mega_cache").fetchone()
    mtime = row[0] if row and row[0] else None
    ext_rows = conn.execute(
        "SELECT SUBSTR(file_name, -4) as ext, COUNT(*) as cnt FROM mega_cache "
        "GROUP BY ext ORDER BY cnt DESC LIMIT 10"
    ).fetchall()
    recent = conn.execute(
        "SELECT file_name, file_size, created_at FROM mega_cache ORDER BY id DESC LIMIT 5"
    ).fetchall()
    conn.close()
    return {
        "total": total,
        "with_links": with_links,
        "without_links": total - with_links,
        "total_size": total_size,
        "last_update": mtime,
        "extensions": [dict(r) for r in ext_rows],
        "recent": [dict(r) for r in recent],
    }


# ─── Problem Reports ───


def create_report(sn: str, problem_type: str, os_type: str = "",
                  os_version: str = "", matched_filenames: str = "",
                  description: str = "", field_name: str = "") -> int:
    conn = get_conn()
    cur = conn.execute(
        "INSERT INTO problem_reports (sn, problem_type, os_type, os_version, matched_filenames, description, field_name) "
        "VALUES (?, ?, ?, ?, ?, ?, ?)",
        (sn, problem_type, os_type, os_version, matched_filenames, description, field_name),
    )
    report_id = cur.lastrowid
    conn.commit()
    mark_dirty()
    conn.close()
    return report_id


def get_reports(status: str | None = None, limit: int = 50) -> list[dict]:
    conn = get_conn()
    if status:
        rows = conn.execute(
            "SELECT * FROM problem_reports WHERE status = ? ORDER BY created_at DESC LIMIT ?",
            (status, limit),
        ).fetchall()
    else:
        rows = conn.execute(
            "SELECT * FROM problem_reports ORDER BY created_at DESC LIMIT ?",
            (limit,),
        ).fetchall()
    conn.close()
    return [dict(r) for r in rows]


def update_report(report_id: int, status: str, resolution_note: str = "") -> bool:
    conn = get_conn()
    cur = conn.execute(
        "UPDATE problem_reports SET status = ?, resolved_at = CURRENT_TIMESTAMP, resolution_note = ? WHERE id = ?",
        (status, resolution_note, report_id),
    )
    conn.commit()
    mark_dirty()
    affected = cur.rowcount > 0
    conn.close()
    return affected


def delete_report(report_id: int) -> bool:
    conn = get_conn()
    cur = conn.execute("DELETE FROM problem_reports WHERE id = ?", (report_id,))
    conn.commit()
    mark_dirty()
    affected = cur.rowcount > 0
    conn.close()
    return affected


# ─── SN File Maps ───


def list_sn_file_maps(limit: int = 100) -> list[dict]:
    conn = get_conn()
    rows = conn.execute(
        "SELECT * FROM sn_file_maps ORDER BY updated_at DESC LIMIT ?",
        (limit,),
    ).fetchall()
    conn.close()
    return [dict(r) for r in rows]


def get_sn_file_map(sn: str) -> dict | None:
    conn = get_conn()
    row = conn.execute(
        "SELECT * FROM sn_file_maps WHERE sn = ?", (sn,)
    ).fetchone()
    conn.close()
    return dict(row) if row else None


def upsert_sn_file_map(sn: str, files: list[str], note: str = "") -> int:
    import json
    conn = get_conn()
    existing = conn.execute(
        "SELECT id FROM sn_file_maps WHERE sn = ?", (sn,)
    ).fetchone()
    now = datetime.now().isoformat()
    if existing:
        conn.execute(
            "UPDATE sn_file_maps SET files = ?, note = ?, updated_at = ? WHERE id = ?",
            (json.dumps(files), note, now, existing["id"]),
        )
        map_id = existing["id"]
    else:
        cur = conn.execute(
            "INSERT INTO sn_file_maps (sn, files, note, updated_at) VALUES (?, ?, ?, ?)",
            (sn, json.dumps(files), note, now),
        )
        map_id = cur.lastrowid
    conn.commit()
    mark_dirty()
    conn.close()
    return map_id


def delete_sn_file_map(map_id: int) -> bool:
    conn = get_conn()
    cur = conn.execute("DELETE FROM sn_file_maps WHERE id = ?", (map_id,))
    conn.commit()
    mark_dirty()
    affected = cur.rowcount > 0
    conn.close()
    return affected


# ─── OS File Maps ───


def list_os_file_maps(limit: int = 100) -> list[dict]:
    conn = get_conn()
    rows = conn.execute(
        "SELECT * FROM os_file_maps ORDER BY updated_at DESC LIMIT ?",
        (limit,),
    ).fetchall()
    conn.close()
    return [dict(r) for r in rows]


def get_os_file_map(os_version: str) -> dict | None:
    conn = get_conn()
    row = conn.execute(
        "SELECT * FROM os_file_maps WHERE os_version = ?", (os_version,)
    ).fetchone()
    conn.close()
    return dict(row) if row else None


def upsert_os_file_map(os_version: str, files: list[str], note: str = "") -> int:
    import json
    conn = get_conn()
    existing = conn.execute(
        "SELECT id FROM os_file_maps WHERE os_version = ?", (os_version,)
    ).fetchone()
    now = datetime.now().isoformat()
    if existing:
        conn.execute(
            "UPDATE os_file_maps SET files = ?, note = ?, updated_at = ? WHERE id = ?",
            (json.dumps(files), note, now, existing["id"]),
        )
        map_id = existing["id"]
    else:
        cur = conn.execute(
            "INSERT INTO os_file_maps (os_version, files, note, updated_at) VALUES (?, ?, ?, ?)",
            (os_version, json.dumps(files), note, now),
        )
        map_id = cur.lastrowid
    conn.commit()
    mark_dirty()
    conn.close()
    return map_id


def delete_os_file_map(map_id: int) -> bool:
    conn = get_conn()
    cur = conn.execute("DELETE FROM os_file_maps WHERE id = ?", (map_id,))
    conn.commit()
    mark_dirty()
    affected = cur.rowcount > 0
    conn.close()
    return affected


# ─── App Settings ───


def get_setting(key: str, default: str = "") -> str:
    conn = get_conn()
    row = conn.execute(
        "SELECT value FROM app_settings WHERE key = ?", (key,)
    ).fetchone()
    conn.close()
    return row["value"] if row else default


def set_setting(key: str, value: str):
    conn = get_conn()
    conn.execute(
        "INSERT INTO app_settings (key, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP) "
        "ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP",
        (key, value),
    )
    conn.commit()
    mark_dirty()
    conn.close()


# ─── MES Query Cache ───


def get_mes_cache(sn: str) -> dict | None:
    conn = get_conn()
    row = conn.execute(
        "SELECT sn, raw_json, created_at FROM mes_cache WHERE sn = ?", (sn,)
    ).fetchone()
    conn.close()
    return dict(row) if row else None


def upsert_mes_cache(sn: str, raw_json: str):
    conn = get_conn()
    conn.execute(
        "INSERT OR REPLACE INTO mes_cache (sn, raw_json, created_at) "
        "VALUES (?, ?, CURRENT_TIMESTAMP)",
        (sn, raw_json),
    )
    conn.commit()
    mark_dirty()
    conn.close()


# ─── Access Profiles ───
# One row per access code. `visible_fields` is the authoritative list of MES keys
# the code may see; the API strips everything else before responding.


def _profile_row(row) -> dict | None:
    if not row:
        return None
    d = dict(row)
    try:
        d["visible_fields"] = json.loads(d.get("visible_fields") or "[]")
    except (json.JSONDecodeError, TypeError):
        d["visible_fields"] = []
    d["is_admin"] = bool(d["is_admin"])
    d["enabled"] = bool(d["enabled"])
    return d


def list_access_profiles() -> list[dict]:
    conn = get_conn()
    rows = conn.execute(
        "SELECT * FROM access_profiles ORDER BY is_admin DESC, id"
    ).fetchall()
    conn.close()
    return [_profile_row(r) for r in rows]


def get_access_profile(profile_id: int) -> dict | None:
    conn = get_conn()
    row = conn.execute(
        "SELECT * FROM access_profiles WHERE id = ?", (profile_id,)
    ).fetchone()
    conn.close()
    return _profile_row(row)


def get_profile_by_code(code: str) -> dict | None:
    if not code:
        return None
    conn = get_conn()
    row = conn.execute(
        "SELECT * FROM access_profiles WHERE code = ?", (code,)
    ).fetchone()
    conn.close()
    return _profile_row(row)


def create_access_profile(
    code: str,
    name: str = "",
    is_admin: bool = False,
    visible_fields: list[str] | None = None,
    enabled: bool = True,
) -> int:
    conn = get_conn()
    cur = conn.execute(
        "INSERT INTO access_profiles (code, name, is_admin, visible_fields, enabled) "
        "VALUES (?, ?, ?, ?, ?)",
        (code, name, 1 if is_admin else 0, json.dumps(visible_fields or []), 1 if enabled else 0),
    )
    conn.commit()
    mark_dirty()
    pid = cur.lastrowid
    conn.close()
    return pid


def update_access_profile(profile_id: int, **kwargs) -> bool:
    allowed = {"code", "name", "is_admin", "visible_fields", "enabled"}
    sets, params = [], []
    for key, value in kwargs.items():
        if key not in allowed:
            continue
        if key == "visible_fields":
            value = json.dumps(value or [])
        elif key in ("is_admin", "enabled"):
            value = 1 if value else 0
        sets.append(f"{key} = ?")
        params.append(value)
    if not sets:
        return False
    params.append(profile_id)
    conn = get_conn()
    cur = conn.execute(
        f"UPDATE access_profiles SET {', '.join(sets)}, updated_at = CURRENT_TIMESTAMP "
        "WHERE id = ?",
        params,
    )
    conn.commit()
    mark_dirty()
    ok = cur.rowcount > 0
    conn.close()
    return ok


def delete_access_profile(profile_id: int) -> bool:
    conn = get_conn()
    cur = conn.execute("DELETE FROM access_profiles WHERE id = ?", (profile_id,))
    conn.commit()
    mark_dirty()
    ok = cur.rowcount > 0
    conn.close()
    return ok


def access_profiles_fingerprint() -> str:
    """Hash of every profile's code + field set + enabled flag.

    Embedded in access tokens: any edit revokes all outstanding tokens at once.
    """
    import hashlib

    parts = [
        f"{p['id']}:{p['code']}:{int(p['enabled'])}:{','.join(sorted(p['visible_fields']))}"
        for p in list_access_profiles()
    ]
    return hashlib.sha256("|".join(parts).encode()).hexdigest()[:16]


# ─── Legacy single access code (kept for the /access-code admin endpoint) ───


def _primary_user_profile() -> dict | None:
    conn = get_conn()
    row = conn.execute(
        "SELECT * FROM access_profiles WHERE is_admin = 0 ORDER BY id LIMIT 1"
    ).fetchone()
    conn.close()
    return _profile_row(row)


def get_mes_access_code() -> str:
    profile = _primary_user_profile()
    if profile:
        return profile["code"]
    return get_setting("mes_access_code", "") or s.MES_ACCESS_CODE


def set_mes_access_code(code: str):
    profile = _primary_user_profile()
    if profile:
        update_access_profile(profile["id"], code=code)
    else:
        create_access_profile(code, "用户", False, [])
    set_setting("mes_access_code", code)


# ─── MES Query Logs (monitoring) ───


def log_mes_query(sn: str, cached: bool = False, status: str = "ok", duration_ms: int = 0):
    conn = get_conn()
    conn.execute(
        "INSERT INTO mes_query_logs (sn, cached, status, duration_ms) VALUES (?, ?, ?, ?)",
        (sn, 1 if cached else 0, status, duration_ms),
    )
    conn.commit()
    conn.close()


def get_mes_monitoring_stats() -> dict:
    conn = get_conn()
    total = conn.execute("SELECT COUNT(*) FROM mes_query_logs").fetchone()[0]
    today = conn.execute(
        "SELECT COUNT(*) FROM mes_query_logs WHERE date(created_at)=date('now')"
    ).fetchone()[0]
    success = conn.execute(
        "SELECT COUNT(*) FROM mes_query_logs WHERE status='ok'"
    ).fetchone()[0]
    errors = conn.execute(
        "SELECT COUNT(*) FROM mes_query_logs WHERE status='error'"
    ).fetchone()[0]
    cache_hits = conn.execute(
        "SELECT COUNT(*) FROM mes_query_logs WHERE cached=1"
    ).fetchone()[0]
    unique_sn = conn.execute(
        "SELECT COUNT(DISTINCT sn) FROM mes_query_logs"
    ).fetchone()[0]
    avg_ms = conn.execute(
        "SELECT COALESCE(AVG(duration_ms), 0) FROM mes_query_logs WHERE status='ok'"
    ).fetchone()[0]
    recent = conn.execute(
        "SELECT * FROM mes_query_logs ORDER BY created_at DESC LIMIT 50"
    ).fetchall()
    daily = conn.execute(
        "SELECT date(created_at) as day, COUNT(*) as cnt FROM mes_query_logs "
        "WHERE created_at >= datetime('now', '-30 days') GROUP BY date(created_at) ORDER BY day"
    ).fetchall()
    top_sn = conn.execute(
        "SELECT sn, COUNT(*) as cnt FROM mes_query_logs GROUP BY sn ORDER BY cnt DESC LIMIT 10"
    ).fetchall()
    total_reports = conn.execute("SELECT COUNT(*) FROM problem_reports").fetchone()[0]
    pending_reports = conn.execute(
        "SELECT COUNT(*) FROM problem_reports WHERE status='pending'"
    ).fetchone()[0]
    os_maps = conn.execute("SELECT COUNT(*) FROM os_file_maps").fetchone()[0]
    sn_maps = conn.execute("SELECT COUNT(*) FROM sn_file_maps").fetchone()[0]
    conn.close()
    return {
        "total_queries": total,
        "today_queries": today,
        "success_queries": success,
        "error_queries": errors,
        "cache_hits": cache_hits,
        "unique_sn": unique_sn,
        "avg_duration_ms": int(avg_ms or 0),
        "recent_queries": [dict(r) for r in recent],
        "daily_queries": [dict(r) for r in daily],
        "top_sn": [dict(r) for r in top_sn],
        "total_reports": total_reports,
        "pending_reports": pending_reports,
        "os_map_count": os_maps,
        "sn_map_count": sn_maps,
    }


def lookup_os_file_map(os_version: str) -> dict | None:
    """Return {os_version, files, note} for an exact OS version, or None."""
    import json

    row = get_os_file_map(os_version)
    if not row:
        return None
    files = row.get("files")
    if isinstance(files, str):
        try:
            files = json.loads(files)
        except (ValueError, TypeError):
            files = []
    return {
        "os_version": row.get("os_version", ""),
        "files": files or [],
        "note": row.get("note", ""),
    }