File size: 41,177 Bytes
cd5aabe
 
 
3b6d807
cd5aabe
 
787d6e0
cd5aabe
d2ae3d7
 
cd5aabe
 
 
d5219c3
 
 
 
 
 
 
 
 
 
46b1977
d5219c3
cd5aabe
46b1977
cd5aabe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b6d807
 
 
cd5aabe
3b6d807
cd5aabe
 
3b6d807
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd5aabe
 
 
 
 
 
3b6d807
cd5aabe
 
3b6d807
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd5aabe
 
787d6e0
 
 
 
 
 
 
 
cd5aabe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
606732d
cd5aabe
d2ae3d7
cd5aabe
 
d2ae3d7
cd5aabe
 
 
 
 
 
 
 
 
 
 
606732d
d2ae3d7
 
 
cd5aabe
d2ae3d7
cd5aabe
 
 
 
 
 
 
 
606732d
cd5aabe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
606732d
cd5aabe
d2ae3d7
cd5aabe
 
 
 
 
 
 
 
606732d
75a5800
cd5aabe
 
834f756
cd5aabe
 
 
 
 
 
 
 
f6571ee
 
d2ae3d7
 
 
606732d
 
 
834f756
 
 
cd5aabe
 
 
 
 
 
 
 
 
 
 
606732d
 
cd5aabe
 
 
 
 
 
 
 
 
 
834f756
 
 
606732d
75a5800
834f756
cd5aabe
 
 
 
 
 
 
 
f6571ee
 
d2ae3d7
 
 
606732d
 
 
834f756
 
 
cd5aabe
 
 
 
 
 
 
 
 
 
 
dae0157
 
 
 
 
 
 
cd5aabe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
606732d
 
cd5aabe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efa793f
cd5aabe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f26f9a
 
 
 
 
 
 
 
 
 
d2ae3d7
8f26f9a
 
d2ae3d7
8f26f9a
 
 
 
 
 
 
 
 
d2ae3d7
 
 
8f26f9a
d2ae3d7
8f26f9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2ae3d7
8f26f9a
 
 
 
 
 
 
 
2c9c1e9
20c1888
 
 
 
399f70f
 
2c9c1e9
399f70f
2c9c1e9
 
20c1888
399f70f
 
 
 
 
2c9c1e9
 
8c9cf09
 
 
 
20c1888
399f70f
8c9cf09
 
 
 
 
 
 
 
2c9c1e9
8c9cf09
 
20c1888
 
 
399f70f
 
 
 
 
 
2c9c1e9
20c1888
 
399f70f
 
20c1888
 
8c9cf09
 
 
 
 
 
 
399f70f
8c9cf09
399f70f
2c9c1e9
 
 
606732d
 
 
 
 
 
 
 
 
 
e8d7d94
606732d
 
 
e8d7d94
606732d
 
 
e8d7d94
606732d
e8d7d94
606732d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bda6cb2
606732d
 
 
eca1538
606732d
 
 
 
 
 
 
 
 
 
 
 
 
 
e8d7d94
606732d
 
 
e8d7d94
606732d
 
 
e8d7d94
606732d
e8d7d94
606732d
 
 
 
 
 
 
640e3c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2ae3d7
 
 
640e3c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd5aabe
 
 
 
 
 
 
606732d
cd5aabe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efa793f
 
cd5aabe
 
 
 
 
787d6e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd5aabe
 
 
 
 
 
 
 
 
 
787d6e0
cd5aabe
 
 
 
606732d
 
787d6e0
 
 
 
 
 
 
 
d2ae3d7
 
 
 
 
 
 
 
 
787d6e0
 
 
 
 
d2ae3d7
787d6e0
 
 
 
 
 
 
 
 
 
d2ae3d7
787d6e0
 
 
 
46b1977
 
35f1fa2
d2ae3d7
787d6e0
 
 
 
 
 
d774232
 
1e42389
35f1fa2
 
 
 
f3a8902
35f1fa2
 
 
f3a8902
787d6e0
4d76fa1
 
35f1fa2
46b1977
35f1fa2
4d76fa1
 
 
 
 
 
 
 
 
 
 
46b1977
d2ae3d7
787d6e0
35f1fa2
 
 
f3a8902
 
 
 
 
 
d774232
 
787d6e0
35f1fa2
46b1977
35f1fa2
4d76fa1
 
 
 
 
 
 
 
 
 
 
46b1977
d2ae3d7
787d6e0
35f1fa2
 
 
f3a8902
 
 
 
 
787d6e0
 
f3a8902
787d6e0
 
 
35f1fa2
 
d774232
787d6e0
35f1fa2
787d6e0
 
 
 
 
f3a8902
787d6e0
 
 
46b1977
787d6e0
35f1fa2
 
787d6e0
 
 
 
 
 
6507333
d2ae3d7
2c9c1e9
d2ae3d7
 
2c9c1e9
 
 
 
 
 
 
 
 
 
d2ae3d7
2c9c1e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2ae3d7
787d6e0
 
6507333
4d76fa1
787d6e0
 
d2ae3d7
787d6e0
46b1977
35f1fa2
 
d2ae3d7
787d6e0
6507333
 
d2ae3d7
6507333
 
44d459b
 
6507333
 
 
 
787d6e0
 
 
 
 
 
 
 
6507333
46b1977
787d6e0
 
35f1fa2
787d6e0
35f1fa2
4d76fa1
 
787d6e0
 
46b1977
35f1fa2
fcd684b
35f1fa2
 
d2ae3d7
35f1fa2
4d76fa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35f1fa2
 
787d6e0
4d76fa1
787d6e0
46b1977
35f1fa2
fcd684b
35f1fa2
 
d2ae3d7
35f1fa2
4d76fa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35f1fa2
 
787d6e0
4d76fa1
787d6e0
4d76fa1
787d6e0
4d76fa1
 
 
 
 
 
787d6e0
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1977
 
 
 
 
 
 
787d6e0
 
 
46b1977
787d6e0
 
 
 
46b1977
 
787d6e0
 
6507333
fcd684b
787d6e0
 
44d459b
787d6e0
 
 
 
 
46b1977
 
787d6e0
 
 
 
 
45141ae
35f1fa2
787d6e0
35f1fa2
 
787d6e0
35f1fa2
787d6e0
 
 
6507333
46b1977
787d6e0
 
 
46b1977
606732d
 
 
0f7a7b0
aa77e89
92132e8
32a07cf
e8d7d94
606732d
c63f9e6
92132e8
606732d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import asyncio
import json
import os
import time
from contextlib import asynccontextmanager
from datetime import datetime
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple

from client_source import current_client_source, validate_client_source

import aiomysql
from aiomysql.cursors import DictCursor

from config import (
    IMAGES_DIR,
    logger,
    MYSQL_HOST,
    MYSQL_PORT,
    MYSQL_DB,
    MYSQL_USER,
    MYSQL_PASSWORD,
    MYSQL_POOL_MIN_SIZE,
    MYSQL_POOL_MAX_SIZE,
    LEADERBOARD_DAYS_LIMIT,
)


_pool: Optional[aiomysql.Pool] = None
_pool_lock = asyncio.Lock()


async def init_mysql_pool() -> aiomysql.Pool:
  """初始化 MySQL 连接池"""
  global _pool
  if _pool is not None:
    return _pool

  async with _pool_lock:
    if _pool is not None:
      return _pool
    try:
      _pool = await aiomysql.create_pool(
          host=MYSQL_HOST,
          port=MYSQL_PORT,
          user=MYSQL_USER,
          password=MYSQL_PASSWORD,
          db=MYSQL_DB,
          minsize=MYSQL_POOL_MIN_SIZE,
          maxsize=MYSQL_POOL_MAX_SIZE,
          autocommit=True,
          charset="utf8mb4",
          cursorclass=DictCursor,
      )
      logger.info(
          "MySQL 连接池初始化成功,host=%s db=%s",
          MYSQL_HOST,
          MYSQL_DB,
      )
    except Exception as exc:
      logger.error(f"初始化 MySQL 连接池失败: {exc}")
      raise
  return _pool


async def close_mysql_pool() -> None:
  """关闭 MySQL 连接池"""
  global _pool
  if _pool is None:
    return

  async with _pool_lock:
    if _pool is None:
      return
    _pool.close()
    await _pool.wait_closed()
    _pool = None
    logger.info("MySQL 连接池已关闭")


@asynccontextmanager
async def get_connection():
  """获取连接池中的连接"""
  if _pool is None:
    await init_mysql_pool()
  assert _pool is not None
  conn = await _pool.acquire()
  try:
    yield conn
  finally:
    _pool.release(conn)


async def execute(
    query: str, params: Sequence[Any] | Dict[str, Any] | None = None
) -> int:
  """执行写入类 SQL"""
  start_time = time.perf_counter()
  async with get_connection() as conn:
    async with conn.cursor() as cursor:
      try:
        await cursor.execute(query, params or ())
        affected = cursor.rowcount
        duration = (time.perf_counter() - start_time) * 1000
        formatted_query = " ".join(query.split())
        logger.info(
            "SQL Execute: %s | Params: %s | Affected: %d | Cost: %.2fms",
            formatted_query,
            params,
            affected,
            duration,
        )
        return affected
      except Exception as exc:
        duration = (time.perf_counter() - start_time) * 1000
        formatted_query = " ".join(query.split())
        logger.error(
            "SQL Execute Failed: %s | Params: %s | Cost: %.2fms | Error: %s",
            formatted_query,
            params,
            duration,
            exc,
        )
        raise


async def fetch_all(
    query: str, params: Sequence[Any] | Dict[str, Any] | None = None
) -> List[Dict[str, Any]]:
  """执行查询并返回全部结果"""
  start_time = time.perf_counter()
  async with get_connection() as conn:
    async with conn.cursor() as cursor:
      try:
        await cursor.execute(query, params or ())
        rows = await cursor.fetchall()
        duration = (time.perf_counter() - start_time) * 1000
        formatted_query = " ".join(query.split())
        logger.info(
            "SQL Query: %s | Params: %s | Rows: %d | Cost: %.2fms",
            formatted_query,
            params,
            len(rows),
            duration,
        )
        return list(rows)
      except Exception as exc:
        duration = (time.perf_counter() - start_time) * 1000
        formatted_query = " ".join(query.split())
        logger.error(
            "SQL Query Failed: %s | Params: %s | Cost: %.2fms | Error: %s",
            formatted_query,
            params,
            duration,
            exc,
        )
        raise


async def fetch_one(
    query: str, params: Sequence[Any] | Dict[str, Any] | None = None
) -> Optional[Dict[str, Any]]:
  """执行查询并返回单条结果"""
  rows = await fetch_all(query, params)
  return rows[0] if rows else None


def _serialize_extra(extra: Optional[Dict[str, Any]]) -> Optional[str]:
  if extra is None:
    return None
  try:
    return json.dumps(extra, ensure_ascii=False)
  except Exception:
    logger.warning("无法序列化 extra_metadata,已忽略")
    return None


async def upsert_image_record(
    *,
    file_path: str,
    category: str,
    nickname: Optional[str],
    score: float,
    is_cropped_face: bool,
    size_bytes: int,
    last_modified: datetime,
    bos_uploaded: bool,
    hostname: Optional[str] = None,
    region: Optional[str] = None,
    extra_metadata: Optional[Dict[str, Any]] = None,
    client_source: Optional[str] = None,
) -> None:
  """写入或更新图片记录"""
  source = validate_client_source(client_source if client_source is not None else current_client_source.get())
  query = """
        INSERT INTO tpl_app_processed_images (
            file_path,
            category,
            nickname,
            score,
            is_cropped_face,
            size_bytes,
            last_modified,
            bos_uploaded,
            hostname,
            region,
            extra_metadata,
            client_source
        ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
        ON DUPLICATE KEY UPDATE
            client_source = IF(client_source = 'unknown', VALUES(client_source), client_source),
            category = VALUES(category),
            nickname = VALUES(nickname),
            score = VALUES(score),
            is_cropped_face = VALUES(is_cropped_face),
            size_bytes = VALUES(size_bytes),
            last_modified = VALUES(last_modified),
            bos_uploaded = VALUES(bos_uploaded),
            hostname = VALUES(hostname),
            region = VALUES(region),
            extra_metadata = VALUES(extra_metadata),
            updated_at = CURRENT_TIMESTAMP
    """
  extra_value = _serialize_extra(extra_metadata)
  await execute(
      query,
      (
        file_path,
        category,
        nickname,
        score,
        1 if is_cropped_face else 0,
        size_bytes,
        last_modified,
        1 if bos_uploaded else 0,
        hostname,
        region,
        extra_value,
        source,
      ),
  )


async def fetch_paged_image_records(
    *,
    category: Optional[str],
    nickname: Optional[str],
    region: Optional[str] = None,
    platform: Optional[str] = None,
    offset: int,
    limit: int,
    is_cropped_face: Optional[int] = None,
) -> List[Dict[str, Any]]:
  """按条件分页查询图片记录"""
  where_clauses: List[str] = []
  params: List[Any] = []
  if category and category != "all":
    where_clauses.append("category = %s")
    params.append(category)
  if nickname:
    where_clauses.append("nickname LIKE %s")
    params.append(f"{nickname}%")
  if platform in {"android", "ios", "web", "wechat", "miniprogram"}:
    where_clauses.append("client_source = %s")
    params.append("wechat" if platform == "miniprogram" else platform)
  if region:
    where_clauses.append("region = %s")
    params.append(region)
  if is_cropped_face is not None:
    where_clauses.append("is_cropped_face = %s")
    params.append(is_cropped_face)
  where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
  query = f"""
        SELECT
            file_path,
            category,
            nickname,
            score,
            is_cropped_face,
            size_bytes,
            last_modified,
            bos_uploaded,
            hostname,
            region
        FROM tpl_app_processed_images
        {where_sql}
        ORDER BY last_modified DESC, id DESC
        LIMIT %s OFFSET %s
    """
  params.extend([limit, offset])
  return await fetch_all(query, params)


async def count_image_records(
    *,
    category: Optional[str],
    nickname: Optional[str],
    region: Optional[str] = None,
    platform: Optional[str] = None,
    is_cropped_face: Optional[int] = None,
) -> int:
  """按条件统计图片记录数量"""
  where_clauses: List[str] = []
  params: List[Any] = []
  if category and category != "all":
    where_clauses.append("category = %s")
    params.append(category)
  if nickname:
    where_clauses.append("nickname LIKE %s")
    params.append(f"{nickname}%")
  if platform in {"android", "ios", "web", "wechat", "miniprogram"}:
    where_clauses.append("client_source = %s")
    params.append("wechat" if platform == "miniprogram" else platform)
  if region:
    where_clauses.append("region = %s")
    params.append(region)
  if is_cropped_face is not None:
    where_clauses.append("is_cropped_face = %s")
    params.append(is_cropped_face)
  where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
  query = f"SELECT COUNT(*) AS total FROM tpl_app_processed_images {where_sql}"
  rows = await fetch_all(query, params)
  if not rows:
    return 0
  return int(rows[0].get("total", 0) or 0)


async def fetch_today_category_counts() -> List[Dict[str, Any]]:
  """统计当天按类别分组的数量"""
  query = """
      SELECT
          COALESCE(category, 'unknown') AS category,
          COUNT(*) AS count
      FROM tpl_app_processed_images
      WHERE last_modified >= CURDATE()
        AND last_modified < DATE_ADD(CURDATE(), INTERVAL 1 DAY)
      GROUP BY COALESCE(category, 'unknown')
    """
  rows = await fetch_all(query)
  return [
    {
      "category": str(row.get("category") or "unknown"),
      "count": int(row.get("count") or 0),
    }
    for row in rows
  ]


async def fetch_records_by_paths(file_paths: Iterable[str]) -> Dict[
  str, Dict[str, Any]]:
  """根据文件名批量查询图片记录"""
  paths = list({path for path in file_paths if path})
  if not paths:
    return {}

  placeholders = ", ".join(["%s"] * len(paths))
  query = f"""
        SELECT
            file_path,
            category,
            nickname,
            score,
            is_cropped_face,
            size_bytes,
            last_modified,
            bos_uploaded,
            hostname,
            region
        FROM tpl_app_processed_images
        WHERE file_path IN ({placeholders})
    """
  rows = await fetch_all(query, paths)
  return {row["file_path"]: row for row in rows}


_IMAGES_DIR_ABS = os.path.abspath(os.path.expanduser(IMAGES_DIR))


def _normalize_file_path(file_path: str) -> Optional[str]:
  """将绝对路径转换为相对 IMAGES_DIR 的文件名"""
  try:
    abs_path = os.path.abspath(os.path.expanduser(file_path))
    if os.path.isdir(abs_path):
      return None
    if os.path.commonpath([_IMAGES_DIR_ABS, abs_path]) != _IMAGES_DIR_ABS:
      return os.path.basename(abs_path)
    rel_path = os.path.relpath(abs_path, _IMAGES_DIR_ABS)
    return rel_path.replace("\\", "/")
  except Exception:
    return None


def infer_category_from_filename(filename: str, default: str = "other") -> str:
  """根据文件名推断类别"""
  lower_name = filename.lower()
  if "_face" in lower_name:
    return "face"
  if lower_name.endswith("_original.webp") or "_original" in lower_name:
    return "original"
  if "_restore" in lower_name:
    return "restore"
  if "_upcolor" in lower_name:
    return "upcolor"
  if "_compress" in lower_name:
    return "compress"
  if "_upscale" in lower_name:
    return "upscale"
  if "_anime_style_" in lower_name:
    return "anime_style"
  if "_grayscale" in lower_name:
    return "grayscale"
  if "_id_photo" in lower_name or "_save_id_photo" in lower_name:
    return "id_photo"
  if "_grid_" in lower_name:
    return "grid"
  if "_rvm_id_photo" in lower_name:
    return "rvm"
  if "_celebrity_" in lower_name or "_celebrity" in lower_name:
    return "celebrity"
  return default


from config import HOSTNAME

async def upsert_device_record(
    *,
    device_id: str,
    device_type: Optional[str] = None,
    device_model: Optional[str] = None,
    os_version: Optional[str] = None,
    app_version: Optional[str] = None,
    timezone: Optional[str] = None,
    region: Optional[str] = None,
    language: Optional[str] = None,
    client_source: str = "android",
) -> None:
    """写入或更新设备记录"""
    source = validate_client_source(client_source)
    query = """
        INSERT INTO tpl_app_user_devices (
            device_id,
            device_type,
            device_model,
            os_version,
            app_version,
            timezone,
            region,
            language,
            client_source
        ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
        ON DUPLICATE KEY UPDATE
            client_source = IF(client_source = 'unknown', VALUES(client_source), client_source),
            device_type = VALUES(device_type),
            device_model = VALUES(device_model),
            os_version = VALUES(os_version),
            app_version = VALUES(app_version),
            timezone = VALUES(timezone),
            region = VALUES(region),
            language = VALUES(language),
            updated_at = CURRENT_TIMESTAMP
    """
    import time
    start_time = time.perf_counter()
    try:
        await execute(
            query,
            (
                device_id,
                device_type,
                device_model,
                os_version,
                app_version,
                timezone,
                region,
                language,
                source,
            ),
        )
        duration = (time.perf_counter() - start_time) * 1000
        logger.info(f"Device record updated for {device_id}, cost: {duration:.2f}ms")
    except Exception as exc:
        logger.warning(f"写入设备记录失败: {exc}")


async def get_user_display_name(device_id: str) -> str:
    return (await get_user_profile(device_id))["display_name"]


async def get_user_profile(device_id: str) -> Dict[str, Any]:
    versioned = os.getenv("ENABLE_PROFILE_REVISIONS", "false").lower() == "true"
    fields = "display_name, display_name_initialized" + (", profile_revision" if versioned else "")
    row = await fetch_one(
        f"SELECT {fields} FROM tpl_app_user_devices WHERE device_id = %s",
        (device_id,),
    )
    name = str(row.get("display_name") or "") if row else ""
    result = {"display_name": name,
              "nickname_initialized": bool(name or (row and row.get("display_name_initialized")))}
    if versioned:
        result["client_revision"] = int(row.get("profile_revision") or 0) if row else 0
    return result


async def set_user_display_name(
    device_id: str,
    display_name: str,
    *,
    initialize_only: bool = False,
    client_revision: Optional[int] = None,
    device_type: Optional[str] = None,
    device_model: Optional[str] = None,
    os_version: Optional[str] = None,
    app_version: Optional[str] = None,
    timezone: Optional[str] = None,
    region: Optional[str] = None,
    language: Optional[str] = None,
) -> None:
    # 独立更新资料,不触碰评分记录的 updated_at、分数或原 nickname。
    # 首次引导同时写入设备资料,单条语句保证昵称与设备信息一起保存。
    # 旧客户端未传或传空的设备字段保留原值;空昵称仍表示主动清空。
    # 条件判断与写入在同一条 SQL 内,避免初始化重试覆盖并发手动改名或清空。
    name_update = ("IF(display_name_initialized = 0 AND display_name = '', VALUES(display_name), display_name)"
                   if initialize_only else "VALUES(display_name)")
    versioned = client_revision is not None and os.getenv("ENABLE_PROFILE_REVISIONS", "false").lower() == "true"
    revision_column = ", profile_revision" if versioned else ""
    revision_value = ", %s" if versioned else ""
    revision_update = ", profile_revision = GREATEST(profile_revision, VALUES(profile_revision))" if versioned else ""
    if versioned and not initialize_only:
        name_update = "IF(VALUES(profile_revision) > profile_revision, VALUES(display_name), display_name)"
    await execute(
        f"""INSERT INTO tpl_app_user_devices (
               device_id, display_name, display_name_initialized, client_source, device_type, device_model,
               os_version, app_version, timezone, region, language{revision_column}
           ) VALUES (%s, %s, 1, 'android', %s, %s, %s, %s, %s, %s, %s{revision_value})
           ON DUPLICATE KEY UPDATE display_name = {name_update},
               display_name_initialized = 1,
               client_source = IF(client_source = 'unknown', VALUES(client_source), client_source),
               device_type = COALESCE(NULLIF(VALUES(device_type), ''), device_type),
               device_model = COALESCE(NULLIF(VALUES(device_model), ''), device_model),
               os_version = COALESCE(NULLIF(VALUES(os_version), ''), os_version),
               app_version = COALESCE(NULLIF(VALUES(app_version), ''), app_version),
               timezone = COALESCE(NULLIF(VALUES(timezone), ''), timezone),
               region = COALESCE(NULLIF(VALUES(region), ''), region),
               language = COALESCE(NULLIF(VALUES(language), ''), language){revision_update}""",
        (device_id, display_name, device_type, device_model, os_version,
         app_version, timezone, region, language) + ((client_revision,) if versioned else ()) ,
    )


async def fetch_user_devices(
    *,
    device_id: Optional[str] = None,
    region: Optional[str] = None,
    offset: int,
    limit: int,
) -> List[Dict[str, Any]]:
    """查询用户设备列表,支持按 device_id 和 region 筛选,按 created_at 倒序"""
    where_clauses: List[str] = []
    params: List[Any] = []

    if device_id:
        where_clauses.append("d.device_id LIKE %s")
        params.append(f"{device_id}%")

    if region:
        where_clauses.append("d.region = %s")
        params.append(region)

    where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else ""

    query = f"""
        SELECT
            d.device_id,
            d.device_type,
            d.device_model,
            d.os_version,
            d.app_version,
            d.timezone,
            d.region,
            d.language,
            d.created_at,
            d.updated_at,
            COALESCE((
                SELECT COUNT(*) 
                FROM tpl_app_processed_images p 
                WHERE p.nickname LIKE CONCAT('android_release_', d.device_id, '%%')
                    AND p.category = 'original'
            ), 0) AS detection_count
        FROM tpl_app_user_devices d
        {where_sql}
        ORDER BY d.updated_at DESC
        LIMIT %s OFFSET %s
    """
    params.extend([limit, offset])
    return await fetch_all(query, params)


async def count_user_devices(
    *,
    device_id: Optional[str] = None,
    region: Optional[str] = None,
) -> int:
    """统计用户设备数量"""
    where_clauses: List[str] = []
    params: List[Any] = []

    if device_id:
        where_clauses.append("d.device_id LIKE %s")
        params.append(f"{device_id}%")

    if region:
        where_clauses.append("d.region = %s")
        params.append(region)

    where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else ""

    query = f"SELECT COUNT(*) AS total FROM tpl_app_user_devices d {where_sql}"
    rows = await fetch_all(query, params)
    if not rows:
        return 0
    return int(rows[0].get("total", 0) or 0)


async def fetch_device_region_stats() -> List[Dict[str, Any]]:
    """统计用户设备按地区分组的数量"""
    query = """
        SELECT
            COALESCE(region, '') AS region,
            COUNT(*) AS count
        FROM tpl_app_user_devices
        GROUP BY COALESCE(region, '')
        ORDER BY count DESC
    """
    return await fetch_all(query)


async def fetch_image_region_stats(
    *,
    category: Optional[str],
    nickname: Optional[str],
    region: Optional[str] = None,
    platform: Optional[str] = None,
    is_cropped_face: Optional[int] = None,
) -> List[Dict[str, Any]]:
    """统计图片记录按地区分组的数量"""
    where_clauses: List[str] = []
    params: List[Any] = []
    if category and category != "all":
        where_clauses.append("category = %s")
        params.append(category)
    if nickname:
        where_clauses.append("nickname LIKE %s")
        params.append(f"{nickname}%")
    if platform in {"android", "ios", "web", "wechat", "miniprogram"}:
        where_clauses.append("client_source = %s")
        params.append("wechat" if platform == "miniprogram" else platform)
    if region:
        where_clauses.append("region = %s")
        params.append(region)
    if is_cropped_face is not None:
        where_clauses.append("is_cropped_face = %s")
        params.append(is_cropped_face)
    where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
    query = f"""
        SELECT
            COALESCE(region, '') AS region,
            COUNT(*) AS count
        FROM tpl_app_processed_images
        {where_sql}
        GROUP BY COALESCE(region, '')
        ORDER BY count DESC
    """
    return await fetch_all(query, params)


async def record_image_creation(
    *,
    file_path: str,
    nickname: Optional[str],
    score: float = 0.0,
    category: Optional[str] = None,
    bos_uploaded: bool = False,
    region: Optional[str] = None,
    extra_metadata: Optional[Dict[str, Any]] = None,
) -> None:
  """
  记录图片元数据到数据库,如果数据库不可用则静默忽略。
  :param file_path: 绝对或相对文件路径
  :param nickname: 用户昵称
  :param score: 关联得分
  :param category: 文件类别,未提供时自动根据文件名推断
  :param bos_uploaded: 是否已上传至 BOS
  :param extra_metadata: 额外信息
  """
  normalized = _normalize_file_path(file_path)
  if normalized is None:
    logger.info("record_image_creation: 无法计算文件名,路径=%s", file_path)
    return

  abs_path = os.path.join(_IMAGES_DIR_ABS, normalized)
  if not os.path.isfile(abs_path):
    logger.info("record_image_creation: 文件不存在,跳过记录 file=%s", abs_path)
    return

  try:
    stat = os.stat(abs_path)
    category_name = category or infer_category_from_filename(normalized)
    # 逻辑调整:支持 ugc_xxxx_face1.webp 这种格式
    is_cropped_face = "_face" in normalized and normalized.count("_") >= 2
    last_modified = datetime.fromtimestamp(stat.st_mtime)

    nickname_value = nickname.strip() if isinstance(nickname,
                                                    str) and nickname.strip() else None

    # 如果 region 为空且为 Android 客户端请求,尝试通过 device_id 回填历史记录的 region
    region_val = region.strip() if isinstance(region, str) and region.strip() else None
    if not region_val and nickname_value and nickname_value.startswith("android_"):
        parts = nickname_value.split("_")
        device_id = parts[-1] if len(parts) >= 3 else None
        if device_id:
            try:
                row = await fetch_one(
                    "SELECT region FROM tpl_app_user_devices WHERE device_id = %s AND region IS NOT NULL AND region != '' LIMIT 1",
                    (device_id,),
                )
                if row and row.get("region"):
                    region_val = row.get("region")
            except Exception:
                pass

    await upsert_image_record(
        file_path=normalized,
        category=category_name,
        nickname=nickname_value,
        score=score,
        is_cropped_face=is_cropped_face,
        size_bytes=stat.st_size,
        last_modified=last_modified,
        bos_uploaded=bos_uploaded,
        hostname=HOSTNAME,
        region=region_val,
        extra_metadata=extra_metadata,
    )
  except Exception as exc:
    logger.warning(f"写入图片记录失败: {exc}")


# 排名与排行榜内存缓存
_RANK_CACHE: Dict[str, Tuple[float, Dict[str, Any]]] = {}
_CACHE_TTL_RANK = 60  # 60秒
_LEADERBOARD_CACHE: Dict[str, Tuple[float, List[Dict[str, Any]]]] = {}
_CACHE_TTL_LEADERBOARD = 180  # 3分钟



def _ranking_scope(source: str, alias: str = "") -> str:
    validate_client_source(source)
    prefix = alias + "." if alias else ""
    condition = f"{prefix}client_source = %s"
    if source == "android":
        condition += f" AND ({prefix}nickname IS NULL OR LEFT({prefix}nickname, 14) <> 'android_debug_')"
    return condition


async def get_face_score_rank(
    score: float,
    region: Optional[str] = None,
    gender: Optional[str] = None,
    age: Optional[str] = None,
    client_source: str = "android",
) -> Dict[str, Any]:
    """
    计算颜值评分在全球和当前地区的排名及击败百分比
    :param score: 颜值分数 (0.0 ~ 100.0)
    :param region: 用户所在地区代码 (如 "CN", "US")
    :param gender: 预留性别
    :param age: 预留年龄
    :return: 包含地区和全球排名统计的字典
    """
    from region_code_utils import get_country_name_by_region_code
    scope = _ranking_scope(client_source)
    score_val = max(0.0, min(100.0, float(score)))
    region_code = region.strip().upper() if region and region.strip() and region.strip().upper() != "GLOBAL" else ""
    region_name = get_country_name_by_region_code(region_code) if region_code else "全球"

    days_limit = max(1, int(LEADERBOARD_DAYS_LIMIT))

    # 排名对小数分数敏感,不能按 0.1 分缓存,否则相邻分数会误用同一名次。
    cache_key = f"{client_source}:{score_val:.4f}:{region_code}:{days_limit}"
    now = time.time()
    if cache_key in _RANK_CACHE:
        cached_time, cached_data = _RANK_CACHE[cache_key]
        if now - cached_time < _CACHE_TTL_RANK:
            return cached_data

    # 统一分数比较表达式:兼容历史库内可能存在的 10 分制 (0~10) 与 100 分制 (0~100)
    score_expr = "(CASE WHEN score <= 10.0 THEN score * 10.0 ELSE score END)"

    success = True
    global_rank = 0
    global_total = 0
    global_percentile = 0.0

    region_rank = 0
    region_total = 0
    region_percentile = 0.0

    try:
        # 排行榜按用户最高分去重;/rank 必须使用完全相同的用户最高分去重口径。
        user_key_expr = "(CASE WHEN nickname IS NOT NULL AND nickname != '' THEN nickname ELSE CONCAT('id_', id) END)"
        g_stats_row = await fetch_one(
            f"""
            SELECT COUNT(*) AS t,
                   COALESCE(SUM(CASE WHEN max_score > %s THEN 1 ELSE 0 END), 0) + 1 AS r
            FROM (
                SELECT {user_key_expr} AS user_key,
                       MAX({score_expr}) AS max_score
                FROM tpl_app_processed_images
                WHERE category = 'face'
                  AND {scope}
                  AND updated_at >= DATE_SUB(NOW(), INTERVAL {days_limit} DAY)
                  AND score > 0
                GROUP BY user_key
            ) AS ranked_users
            """,
            (score_val, client_source)
        )
        if g_stats_row is not None:
            db_g_total = int(g_stats_row.get("t") or 0)
            db_g_rank = int(g_stats_row.get("r") or 1)
            if db_g_total > 0:
                global_total = db_g_total
                global_rank = min(global_total, max(1, db_g_rank))
                # 击败百分比 = (total - rank + 1) / total * 100
                global_percentile = round((global_total - global_rank + 1) / global_total * 100.0, 2)
                global_percentile = max(0.01, min(100.0, global_percentile))

        # 地区排名计算
        if region_code:
            r_stats_row = await fetch_one(
                f"""
                SELECT COUNT(*) AS t,
                       COALESCE(SUM(CASE WHEN max_score > %s THEN 1 ELSE 0 END), 0) + 1 AS r
                FROM (
                    SELECT {user_key_expr} AS user_key,
                           MAX({score_expr}) AS max_score
                    FROM tpl_app_processed_images
                    WHERE category = 'face' AND region = %s
                      AND {scope}
                      AND updated_at >= DATE_SUB(NOW(), INTERVAL {days_limit} DAY)
                      AND score > 0
                    GROUP BY user_key
                ) AS ranked_users
                """,
                (score_val, region_code, client_source)
            )
            if r_stats_row is not None:
                db_r_total = int(r_stats_row.get("t") or 0)
                db_r_rank = int(r_stats_row.get("r") or 1)
                if db_r_total > 0:
                    region_total = db_r_total
                    region_rank = min(region_total, max(1, db_r_rank))
                    region_percentile = round((region_total - region_rank + 1) / region_total * 100.0, 2)
                    region_percentile = max(0.01, min(100.0, region_percentile))
        else:
            region_total = global_total
            region_rank = global_rank
            region_percentile = global_percentile

    except Exception as exc:
        logger.warning(f"获取颜值排名数据库查询异常: {exc}")
        success = False

    result = {
        "success": success,
        "score": score_val,
        "region_code": region_code or "GLOBAL",
        "region_name": region_name,
        "region_rank": region_rank,
        "region_total": region_total,
        "region_percentile": region_percentile,
        "global_rank": global_rank,
        "global_total": global_total,
        "global_percentile": global_percentile,
        "days_limit": days_limit,
    }
    if success:
        _RANK_CACHE[cache_key] = (now, result)
    return result


async def get_face_score_leaderboard(
    region: Optional[str] = None,
    limit: int = 50,
    current_device_id: Optional[str] = None,
    client_source: str = "android",
) -> Dict[str, Any]:
    result = await _get_cached_face_score_leaderboard(region, limit, current_device_id, client_source)
    if client_source != "android" or not result["success"] or not result["items"]:
        return result
    # 排名缓存只保存评分记录;昵称每次批量读取,跨 worker 改名/清空也立即生效。
    # Android 上传格式为 prefix_androidId,历史 android_* 前缀同样兼容。
    device_ids = sorted({item["nickname"].rsplit("_", 1)[-1]
                         for item in result["items"] if item["nickname"].startswith("android_")})
    try:
        names: Dict[str, str] = {}
        if device_ids:
            placeholders = ", ".join(["%s"] * len(device_ids))
            rows = await fetch_all(
                f"SELECT device_id, display_name FROM tpl_app_user_devices WHERE client_source = 'android' AND device_id IN ({placeholders})",
                device_ids,
            )
            names = {row["device_id"]: str(row.get("display_name") or "") for row in rows}
        for item in result["items"]:
            item["display_name"] = names.get(item["nickname"].rsplit("_", 1)[-1], "") if item["nickname"].startswith("android_") else ""
        return result
    except Exception as exc:
        logger.warning("读取排行榜昵称失败: %s", exc)
        return {**result, "success": False, "items": [], "total_records": 0}


async def _get_cached_face_score_leaderboard(
    region: Optional[str] = None,
    limit: int = 50,
    current_device_id: Optional[str] = None,
    client_source: str = "android",
) -> Dict[str, Any]:
    """
    获取颜值评分记录排行榜 Top N (支持地区榜与全球榜)。
    按用户(nickname)去重,每个用户仅保留最高分记录;无昵称的匿名记录独立保留。
    """
    from region_code_utils import get_country_name_by_region_code
    scope = _ranking_scope(client_source, "candidate")
    region_code = region.strip().upper() if region and region.strip() and region.strip().upper() != "GLOBAL" else None
    days_limit = max(1, int(LEADERBOARD_DAYS_LIMIT))
    # limit 会改变缓存内容,必须纳入 key,避免一次小 limit 请求污染后续 Top 50。
    safe_limit = max(1, min(100, int(limit)))
    cache_key = f"{client_source}:{region_code or 'GLOBAL'}:{days_limit}:{safe_limit}"
    now = time.time()

    def response_items(cached_or_fresh_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        device_suffix = f"_{current_device_id}" if current_device_id and client_source == "android" else None
        result_items: List[Dict[str, Any]] = []
        for cached_item in cached_or_fresh_items[:limit]:
            nickname = str(cached_item.get("nickname") or "")
            public_item = dict(cached_item)
            public_item["is_current_user"] = bool(device_suffix and nickname.endswith(device_suffix))
            result_items.append(public_item)
        return result_items

    if cache_key in _LEADERBOARD_CACHE:
        cached_time, cached_items = _LEADERBOARD_CACHE[cache_key]
        if now - cached_time < _CACHE_TTL_LEADERBOARD:
            return {
                "success": True,
                "region_code": region_code or "GLOBAL",
                "region_name": get_country_name_by_region_code(region_code) if region_code else "全球",
                "total_records": len(cached_items),
                "items": response_items(cached_items),
                "days_limit": days_limit,
            }

    success = True
    items = []
    candidate_score_expr = "(CASE WHEN candidate.score <= 10.0 THEN candidate.score * 10.0 ELSE candidate.score END)"
    better_score_expr = "(CASE WHEN better.score <= 10.0 THEN better.score * 10.0 ELSE better.score END)"
    better_scope = _ranking_scope(client_source, "better")
    try:
        if region_code:
            query = f"""
                SELECT candidate.id, {candidate_score_expr} AS score, candidate.region,
                       candidate.nickname, candidate.file_path, candidate.extra_metadata, candidate.updated_at, candidate.created_at
                FROM tpl_app_processed_images AS candidate
                WHERE candidate.category = 'face' AND candidate.score > 0 AND candidate.region = %s
                  AND {scope}
                  AND candidate.updated_at >= DATE_SUB(NOW(), INTERVAL {days_limit} DAY)
                  AND (
                      candidate.nickname IS NULL
                      OR candidate.nickname = ''
                      OR NOT EXISTS (
                          SELECT 1
                          FROM tpl_app_processed_images AS better
                          WHERE better.nickname = candidate.nickname
                            AND better.category = 'face' AND better.score > 0 AND better.region = %s
                            AND {better_scope}
                            AND better.updated_at >= DATE_SUB(NOW(), INTERVAL {days_limit} DAY)
                            AND (
                                {better_score_expr} > {candidate_score_expr}
                                OR ({better_score_expr} = {candidate_score_expr} AND better.id < candidate.id)
                            )
                      )
                  )
                ORDER BY score DESC, candidate.id ASC
                LIMIT {safe_limit}
            """
            rows = await fetch_all(query, (region_code, client_source, region_code, client_source))
        else:
            query = f"""
                SELECT candidate.id, {candidate_score_expr} AS score, candidate.region,
                       candidate.nickname, candidate.file_path, candidate.extra_metadata, candidate.updated_at, candidate.created_at
                FROM tpl_app_processed_images AS candidate
                WHERE candidate.category = 'face' AND candidate.score > 0
                  AND {scope}
                  AND candidate.updated_at >= DATE_SUB(NOW(), INTERVAL {days_limit} DAY)
                  AND (
                      candidate.nickname IS NULL
                      OR candidate.nickname = ''
                      OR NOT EXISTS (
                          SELECT 1
                          FROM tpl_app_processed_images AS better
                          WHERE better.nickname = candidate.nickname
                            AND better.category = 'face' AND better.score > 0
                            AND {better_scope}
                            AND better.updated_at >= DATE_SUB(NOW(), INTERVAL {days_limit} DAY)
                            AND (
                                {better_score_expr} > {candidate_score_expr}
                                OR ({better_score_expr} = {candidate_score_expr} AND better.id < candidate.id)
                            )
                      )
                  )
                ORDER BY score DESC, candidate.id ASC
                LIMIT {safe_limit}
            """
            rows = await fetch_all(query, (client_source, client_source))

        seen_users = set()
        for row in rows:
            raw_nick = str(row.get("nickname") or "").strip()
            user_key = raw_nick if raw_nick else f"id_{row.get('id')}"
            if user_key in seen_users:
                continue
            seen_users.add(user_key)

            row_id = int(row.get("id") or 0)
            score_val = round(float(row.get("score") or 0.0), 2)
            row_region = row.get("region") or region_code or "US"
            row_country_name = get_country_name_by_region_code(row_region)

            meta = row.get("extra_metadata")
            if isinstance(meta, str):
                try:
                    meta = json.loads(meta)
                except Exception:
                    meta = {}
            elif not isinstance(meta, dict):
                meta = {}

            raw_gender = str(meta.get("gender") or "").strip().lower()
            if any(w in raw_gender for w in ["female", "woman", "women", "女", "f"]):
                gender = "Female"
            elif any(w in raw_gender for w in ["male", "man", "men", "男", "m"]):
                gender = "Male"
            else:
                gender = "Female" if (row_id % 2 == 0) else "Male"
            age = str(meta.get("age") or (20 + (row_id % 12)))

            # 确定性假头像 ID (1..16),女 1..8,男 9..16
            if gender == "Female":
                avatar_id = (row_id % 8) + 1
            else:
                avatar_id = (row_id % 8) + 9

            updated_at_val = row.get("updated_at") or row.get("created_at")
            updated_at_str = str(updated_at_val or "")

            items.append({
                "record_id": row_id,
                "file_path": str(row.get("file_path") or ""),
                "rank": len(items) + 1,
                "score": score_val,
                "nickname": str(row.get("nickname") or ""),
                "region_code": row_region,
                "region_name": row_country_name,
                "gender": gender,
                "age": age,
                "avatar_id": avatar_id,
                "created_at": updated_at_str,
                "updated_at": updated_at_str,
            })
            if len(items) >= limit:
                break

    except Exception as exc:
        logger.warning(f"获取颜值排行榜数据库异常: {exc}")
        success = False

    if success:
        _LEADERBOARD_CACHE[cache_key] = (now, items)
    return {
        "success": success,
        "region_code": region_code or "GLOBAL",
        "region_name": get_country_name_by_region_code(region_code) if region_code else "全球",
        "total_records": len(items),
        "items": response_items(items),
        "days_limit": days_limit,
    }



# 清理调试数据 SQL 列表,可在此处增删 SQL
CLEAN_DEBUG_SQLS = [
    "DELETE FROM tpl_app_user_devices WHERE device_model='Xiaomi 23127PN0CC' AND region='CN'",
    "DELETE FROM tpl_app_user_devices WHERE device_id='cfcae0ec66c8b429'",
    "DELETE FROM tpl_app_user_devices WHERE device_id='7bfefa2d7f8c0be3'",
    "DELETE FROM tpl_app_user_devices WHERE device_id='782831daa5e25b35'",
    "DELETE FROM tpl_app_processed_images WHERE nickname LIKE 'android_debug%%'",
    "DELETE FROM tpl_app_processed_images WHERE nickname='string'",
    "DELETE FROM tpl_app_processed_images WHERE nickname='android_release_1b708ef79ac4f484'",
    "DELETE FROM tpl_app_processed_images WHERE nickname='android_release_3912d8c0e7f9c153'",
    "DELETE FROM tpl_app_processed_images WHERE nickname='android_release_782831daa5e25b35'",
    "DELETE FROM tpl_app_processed_images WHERE nickname='9527'",
]


async def clean_debug_data() -> Dict[str, int]:
    """
    清理调试数据
    :return: 返回每个 SQL 影响的行数
    """
    results = {}
    for idx, sql in enumerate(CLEAN_DEBUG_SQLS):
        try:
            affected = await execute(sql)
            results[f"sql_{idx + 1}"] = affected
            logger.info(f"Clean debug SQL #{idx + 1} executed, affected: {affected}")
        except Exception as exc:
            logger.warning(f"Clean debug SQL #{idx + 1} failed: {exc}")
            results[f"sql_{idx + 1}"] = -1
    return results