File size: 39,275 Bytes
adf61ba
 
 
41a6799
ac32648
adf61ba
41a6799
adf61ba
 
 
 
 
 
 
41a6799
 
adf61ba
41a6799
adf61ba
 
5f5ce60
adf61ba
 
5f5ce60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adf61ba
 
41a6799
ac32648
5f5ce60
 
adf61ba
ac32648
5f5ce60
 
 
 
 
adf61ba
 
 
 
 
 
 
 
 
 
 
 
 
 
41a6799
 
 
 
 
 
adf61ba
41a6799
 
ac32648
41a6799
 
 
 
 
 
 
 
adf61ba
ac32648
adf61ba
 
ac32648
adf61ba
 
 
ac32648
 
adf61ba
ac32648
 
 
 
 
 
adf61ba
ac32648
 
 
 
adf61ba
ac32648
 
 
adf61ba
ac32648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adf61ba
ac32648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adf61ba
ac32648
 
 
adf61ba
 
 
ac32648
 
 
 
 
 
 
 
 
 
 
adf61ba
ac32648
 
 
 
 
 
 
 
 
 
 
 
 
adf61ba
ac32648
 
adf61ba
ac32648
 
 
 
adf61ba
ac32648
 
 
 
 
 
 
 
 
 
adf61ba
 
ac32648
 
adf61ba
 
ac32648
 
 
 
 
 
 
 
 
 
adf61ba
 
 
 
ac32648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adf61ba
ac32648
 
 
 
 
41a6799
ac32648
 
 
41a6799
ac32648
 
41a6799
 
 
 
 
 
ac32648
 
 
 
41a6799
 
 
 
ac32648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41a6799
ac32648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41a6799
ac32648
 
 
41a6799
 
ac32648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41a6799
 
ac32648
41a6799
ac32648
 
 
 
41a6799
 
 
ac32648
 
 
 
 
 
 
 
41a6799
ac32648
 
 
 
 
 
 
 
 
 
 
41a6799
 
ac32648
41a6799
ac32648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41a6799
 
ac32648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41a6799
ac32648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adf61ba
41a6799
ac32648
 
adf61ba
41a6799
adf61ba
 
 
 
41a6799
ac32648
41a6799
 
ac32648
 
41a6799
ac32648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
033dc30
ac32648
 
 
 
 
 
 
 
033dc30
ac32648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41a6799
ac32648
 
41a6799
ac32648
41a6799
ac32648
 
 
41a6799
ac32648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41a6799
033dc30
ac32648
41a6799
 
ac32648
 
 
 
 
033dc30
 
 
 
ac32648
41a6799
ac32648
 
 
41a6799
ac32648
41a6799
ac32648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41a6799
ac32648
 
41a6799
 
 
ac32648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adf61ba
ac32648
adf61ba
 
 
 
ac32648
adf61ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41a6799
 
 
ac32648
 
adf61ba
41a6799
adf61ba
 
 
 
56b2946
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
"""
과제 곡고 벑터 DB μΊμ‹œ μ‹œμŠ€ν…œ
- ChromaDBλ₯Ό μ‚¬μš©ν•œ 둜컬 μΊμ‹œ
- 메타 μΊμ‹œ + λ³Έλ¬Έ 벑터 μΊμ‹œ (2개 μ»¬λ ‰μ…˜)
- μ‚¬μš©μž ν”„λ‘œν•„ μ €μž₯ (이메일 기반)
- 맀일 KST 10:00, 22:00 μžλ™ 동기화
- λ°±κ·ΈλΌμš΄λ“œ λ³Έλ¬Έ 인덱싱 (μ„œλΉ„μŠ€ 무쀑단)
- Hugging Face Space 영ꡬ μŠ€ν† λ¦¬μ§€ ν™œμš© (/data)
"""
import os
import json
import hashlib
import threading
import logging
import tempfile
import time
from datetime import datetime, timedelta
from typing import List, Dict, Tuple, Optional, Generator
from pathlib import Path
import pytz

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# ==================== 영ꡬ μŠ€ν† λ¦¬μ§€ μ„€μ • (AETHER νŒ¨ν„΄ 적용) ====================

PERSISTENT_DIR = "/data"
LOCAL_FALLBACK_DIR = "./data"

# μ „μ—­ μΊμ‹œ λ³€μˆ˜ (ν•œ 번만 κ²°μ •)
_STORAGE_BASE_PATH = None

def _try_enable_persistent_storage_via_api() -> bool:
    """HF API둜 Persistent Storage ν™œμ„±ν™” μ‹œλ„"""
    hf_token = os.getenv("HF_TOKEN")
    space_id = os.getenv("SPACE_ID")
    
    if not hf_token:
        logger.warning("⚠️ HF_TOKEN ν™˜κ²½λ³€μˆ˜ μ—†μŒ - API ν™œμ„±ν™” λΆˆκ°€")
        return False
    if not space_id:
        logger.warning("⚠️ SPACE_ID ν™˜κ²½λ³€μˆ˜ μ—†μŒ - HF Spaces ν™˜κ²½μ΄ μ•„λ‹Œ 것 κ°™μŠ΅λ‹ˆλ‹€")
        return False
    
    logger.info(f"πŸ”„ Persistent Storage API ν™œμ„±ν™” μ‹œλ„... Space ID: {space_id}")
    
    try:
        from huggingface_hub import HfApi, SpaceStorage
        api = HfApi(token=hf_token)
        
        try:
            runtime = api.get_space_runtime(repo_id=space_id)
            current_storage = getattr(runtime, 'storage', None)
            if current_storage:
                logger.info(f"βœ… Persistent Storage 이미 ν™œμ„±ν™”λ¨: {current_storage}")
                return True
            else:
                logger.info("πŸ“¦ Persistent Storage λΉ„ν™œμ„±ν™” μƒνƒœ - ν™œμ„±ν™” μ‹œλ„...")
        except Exception as e:
            logger.warning(f"⚠️ Space μƒνƒœ 확인 μ‹€νŒ¨: {e}")
        
        api.request_space_storage(repo_id=space_id, storage=SpaceStorage.SMALL)
        logger.info("βœ… Persistent Storage SMALL ν™œμ„±ν™” μš”μ²­ μ™„λ£Œ!")
        logger.info("⏳ Spaceκ°€ μž¬μ‹œμž‘λ©λ‹ˆλ‹€. μž μ‹œ ν›„ /data 디렉토리가 μƒμ„±λ©λ‹ˆλ‹€.")
        return True
        
    except ImportError:
        logger.warning("⚠️ huggingface_hub 라이브러리 μ—†μŒ")
        return False
    except Exception as e:
        error_msg = str(e)
        if "already" in error_msg.lower() or "exists" in error_msg.lower():
            logger.info(f"βœ… Persistent Storage 이미 ν™œμ„±ν™”λ¨")
            return True
        elif "payment" in error_msg.lower() or "billing" in error_msg.lower():
            logger.warning(f"⚠️ 결제 정보 ν•„μš”: {error_msg}")
        else:
            logger.warning(f"⚠️ API ν™œμ„±ν™” μ‹€νŒ¨: {error_msg}")
        return False

def _determine_storage_path() -> Path:
    """영ꡬ μ €μž₯μ†Œ 경둜 κ²°μ • (AETHER νŒ¨ν„΄)"""
    global _STORAGE_BASE_PATH
    
    # 이미 κ²°μ •λœ 경우 μΊμ‹œ λ°˜ν™˜
    if _STORAGE_BASE_PATH is not None:
        return _STORAGE_BASE_PATH
    
    print("\n" + "=" * 60)
    print("πŸ” CoBIZ μΊμ‹œ μŠ€ν† λ¦¬μ§€ μ΄ˆκΈ°ν™” 쀑...")
    print("=" * 60)
    
    # 1. /data 경둜 확인 (HF Spaces Persistent Storage)
    if os.path.exists(PERSISTENT_DIR):
        try:
            test_file = os.path.join(PERSISTENT_DIR, ".write_test")
            with open(test_file, "w") as f:
                f.write("test")
            os.remove(test_file)
            
            _STORAGE_BASE_PATH = Path(PERSISTENT_DIR)
            logger.info(f"βœ… HF Spaces 영ꡬ μŠ€ν† λ¦¬μ§€ ν™œμ„±ν™”: {PERSISTENT_DIR}")
            
            # κΈ°μ‘΄ 파일 확인
            existing_files = [f for f in os.listdir(PERSISTENT_DIR) 
                           if f.endswith('.db') or f.endswith('.json') or f == 'announcement_cache']
            if existing_files:
                logger.info(f"πŸ“ κΈ°μ‘΄ 파일 발견: {existing_files}")
            else:
                logger.info("πŸ“ κΈ°μ‘΄ 파일 μ—†μŒ (μƒˆλ‘œμš΄ μŠ€ν† λ¦¬μ§€)")
            
            print("=" * 60 + "\n")
            return _STORAGE_BASE_PATH
            
        except Exception as e:
            logger.warning(f"⚠️ /data μ“°κΈ° ν…ŒμŠ€νŠΈ μ‹€νŒ¨: {e}")
    else:
        logger.warning(f"⚠️ {PERSISTENT_DIR} 디렉토리 μ—†μŒ")
        
        # API둜 ν™œμ„±ν™” μ‹œλ„
        logger.info("\nπŸš€ API둜 Persistent Storage ν™œμ„±ν™” μ‹œλ„...")
        if _try_enable_persistent_storage_via_api():
            logger.info("πŸ’‘ API μš”μ²­ μ™„λ£Œ. Space μž¬μ‹œμž‘ ν›„ /data μ‚¬μš© κ°€λŠ₯")
    
    # 2. ν™˜κ²½λ³€μˆ˜λ‘œ μ§€μ •λœ 경둜 확인
    env_path = os.environ.get("PERSISTENT_DATA_DIR")
    if env_path:
        try:
            os.makedirs(env_path, exist_ok=True)
            test_file = os.path.join(env_path, ".write_test")
            with open(test_file, "w") as f:
                f.write("test")
            os.remove(test_file)
            
            _STORAGE_BASE_PATH = Path(env_path)
            logger.info(f"βœ… ν™˜κ²½λ³€μˆ˜ μŠ€ν† λ¦¬μ§€ μ‚¬μš©: {env_path}")
            print("=" * 60 + "\n")
            return _STORAGE_BASE_PATH
        except Exception as e:
            logger.warning(f"⚠️ PERSISTENT_DATA_DIR μ“°κΈ° λΆˆκ°€: {e}")
    
    # 3. 둜컬 폴백 (λΉ„μ˜κ΅¬)
    os.makedirs(LOCAL_FALLBACK_DIR, exist_ok=True)
    _STORAGE_BASE_PATH = Path(LOCAL_FALLBACK_DIR)
    
    logger.warning(f"\n🟑 ν˜„μž¬ 둜컬 μŠ€ν† λ¦¬μ§€ μ‚¬μš©: {LOCAL_FALLBACK_DIR}")
    logger.warning("   ⚠️ μž¬μ‹œμž‘ μ‹œ λͺ¨λ“  데이터가 μ†μ‹€λ©λ‹ˆλ‹€!")
    logger.warning("   πŸ’‘ HF Space Settings β†’ Persistent Storage β†’ Enable ν•„μš”!")
    print("=" * 60 + "\n")
    
    return _STORAGE_BASE_PATH

def get_storage_info() -> dict:
    """μŠ€ν† λ¦¬μ§€ μƒνƒœ 정보 λ°˜ν™˜"""
    base_path = _determine_storage_path()
    cache_dir = base_path / "announcement_cache"
    
    info = {
        "base_path": str(base_path),
        "is_persistent": str(base_path) == PERSISTENT_DIR,
        "cache_dir": str(cache_dir),
        "cache_exists": cache_dir.exists(),
        "files": []
    }
    
    if cache_dir.exists():
        info["files"] = [f for f in os.listdir(cache_dir) if not f.startswith('.')]
    
    return info

def verify_storage_persistence():
    """μŠ€ν† λ¦¬μ§€ μ˜μ†μ„± 검증 (λ””λ²„κΉ…μš©)"""
    base_path = _determine_storage_path()
    cache_dir = base_path / "announcement_cache"
    
    logger.info(f"\nπŸ” μŠ€ν† λ¦¬μ§€ μ˜μ†μ„± 검증:")
    logger.info(f"   기본 경둜: {base_path}")
    logger.info(f"   영ꡬ μ €μž₯: {'βœ… 예' if str(base_path) == PERSISTENT_DIR else '❌ μ•„λ‹ˆμ˜€'}")
    logger.info(f"   μΊμ‹œ 디렉토리: {cache_dir}")
    logger.info(f"   μΊμ‹œ 쑴재: {cache_dir.exists()}")
    
    if cache_dir.exists():
        files = list(cache_dir.iterdir())
        logger.info(f"   파일 수: {len(files)}")
        for f in files[:5]:  # μ΅œλŒ€ 5개만 ν‘œμ‹œ
            logger.info(f"   - {f.name}")

# μ΄ˆκΈ°ν™” μ‹€ν–‰
PERSISTENT_DIR_PATH = _determine_storage_path()
verify_storage_persistence()
# 경둜 μ„€μ • (μ΄ˆκΈ°ν™”λœ PERSISTENT_DIR_PATH μ‚¬μš©)
CACHE_DIR = PERSISTENT_DIR_PATH / "announcement_cache"
DB_PATH = CACHE_DIR / "chroma_db"
METADATA_FILE = CACHE_DIR / "sync_metadata.json"
CONTENT_INDEX_FILE = CACHE_DIR / "content_index_status.json"
PROFILE_DIR = CACHE_DIR / "user_profiles"

# 디렉토리 생성
CACHE_DIR.mkdir(parents=True, exist_ok=True)
PROFILE_DIR.mkdir(parents=True, exist_ok=True)

# μ €μž₯ 경둜 λ‘œκΉ…
logger.info(f"Cache directory: {CACHE_DIR}")
logger.info(f"Profile directory: {PROFILE_DIR}")
logger.info(f"Persistent storage: {'βœ… YES' if str(PERSISTENT_DIR_PATH) == PERSISTENT_DIR else '❌ NO (local only)'}")
try:
    import chromadb
    from chromadb.config import Settings
    CHROMADB_AVAILABLE = True
except ImportError:
    CHROMADB_AVAILABLE = False
    logger.warning("ChromaDB not available. Using JSON fallback.")
try:
    from apscheduler.schedulers.background import BackgroundScheduler
    from apscheduler.triggers.cron import CronTrigger
    SCHEDULER_AVAILABLE = True
except ImportError:
    SCHEDULER_AVAILABLE = False
    logger.warning("APScheduler not available. Auto-sync disabled.")
try:
    from sentence_transformers import SentenceTransformer
    EMBEDDING_AVAILABLE = True
except ImportError:
    EMBEDDING_AVAILABLE = False
    logger.warning("sentence-transformers not available. Using ChromaDB default embedding.")
KST = pytz.timezone('Asia/Seoul')
_embedding_model = None
def get_embedding_model():
    """ν•œκ΅­μ–΄ μž„λ² λ”© λͺ¨λΈ λ‘œλ“œ (싱글톀)"""
    global _embedding_model
    if _embedding_model is None and EMBEDDING_AVAILABLE:
        try:
            _embedding_model = SentenceTransformer('jhgan/ko-sroberta-multitask')
            logger.info("Loaded Korean embedding model: jhgan/ko-sroberta-multitask")
        except Exception as e:
            logger.error(f"Failed to load embedding model: {e}")
    return _embedding_model
class AnnouncementCache:
    """메타 정보 μΊμ‹œ (ChromaDB 기반)"""
    def __init__(self):
        self.client = None
        self.collection = None
        self._init_db()
    def _init_db(self):
        """ChromaDB μ΄ˆκΈ°ν™”"""
        if not CHROMADB_AVAILABLE:
            return
        try:
            self.client = chromadb.PersistentClient(path=str(DB_PATH))
            self.collection = self.client.get_or_create_collection(
                name="announcements",
                metadata={"hnsw:space": "cosine"}
            )
            logger.info(f"ChromaDB initialized at {DB_PATH}")
        except Exception as e:
            logger.error(f"ChromaDB init error: {e}")
            self.client = None
            self.collection = None
    def _generate_id(self, item: dict) -> str:
        """곡고 고유 ID 생성"""
        pblanc_id = item.get("pblancId") or item.get("seq") or ""
        title = item.get("title") or item.get("pblancNm") or ""
        unique_str = f"{pblanc_id}_{title}"
        return hashlib.md5(unique_str.encode()).hexdigest()
    def _item_to_document(self, item: dict) -> str:
        """곡고 정보λ₯Ό κ²€μƒ‰μš© λ¬Έμ„œλ‘œ λ³€ν™˜"""
        parts = []
        title = item.get("title") or item.get("pblancNm") or ""
        if title:
            parts.append(title)
        description = item.get("description") or item.get("bsnsSumryCn") or ""
        if description:
            import re
            description = re.sub(r'<[^>]+>', '', description).strip()
            parts.append(description[:500])
        author = item.get("author") or item.get("jrsdInsttNm") or ""
        if author:
            parts.append(author)
        category = item.get("lcategory") or item.get("pldirSportRealmLclasCodeNm") or ""
        if category:
            parts.append(category)
        hash_tags = item.get("hashTags") or ""
        if hash_tags:
            parts.append(hash_tags)
        target = item.get("trgetNm") or ""
        if target:
            parts.append(target)
        return " ".join(parts)
    def _item_to_metadata(self, item: dict) -> dict:
        """곡고 정보λ₯Ό λ©”νƒ€λ°μ΄ν„°λ‘œ λ³€ν™˜"""
        def safe_str(val):
            if val is None:
                return ""
            return str(val)[:500]
        return {
            "pblancId": safe_str(item.get("pblancId") or item.get("seq")),
            "title": safe_str(item.get("title") or item.get("pblancNm")),
            "author": safe_str(item.get("author") or item.get("jrsdInsttNm")),
            "category": safe_str(item.get("lcategory") or item.get("pldirSportRealmLclasCodeNm")),
            "reqstDt": safe_str(item.get("reqstDt") or item.get("reqstBeginEndDe")),
            "pubDate": safe_str(item.get("pubDate") or item.get("creatPnttm")),
            "link": safe_str(item.get("link") or item.get("pblancUrl")),
            "hashTags": safe_str(item.get("hashTags")),
            "target": safe_str(item.get("trgetNm")),
            "excInsttNm": safe_str(item.get("excInsttNm")),
            "fileUrl": safe_str(item.get("flpthNm")),
            "fileName": safe_str(item.get("fileNm")),
            "printFileUrl": safe_str(item.get("printFlpthNm")),
            "printFileName": safe_str(item.get("printFileNm")),
            "description": safe_str(item.get("description") or item.get("bsnsSumryCn")),
        }
    def bulk_upsert(self, items: List[dict]) -> Tuple[int, int]:
        """λŒ€λŸ‰ 데이터 μ‚½μž…/μ—…λ°μ΄νŠΈ"""
        if not self.collection or not items:
            return 0, 0
        added = 0
        updated = 0
        batch_size = 100
        for i in range(0, len(items), batch_size):
            batch = items[i:i+batch_size]
            ids = []
            documents = []
            metadatas = []
            for item in batch:
                doc_id = self._generate_id(item)
                ids.append(doc_id)
                documents.append(self._item_to_document(item))
                metadatas.append(self._item_to_metadata(item))
            try:
                existing = self.collection.get(ids=ids)
                existing_ids = set(existing['ids']) if existing['ids'] else set()
                self.collection.upsert(
                    ids=ids,
                    documents=documents,
                    metadatas=metadatas
                )
                for doc_id in ids:
                    if doc_id in existing_ids:
                        updated += 1
                    else:
                        added += 1
                logger.info(f"Upserted batch {i//batch_size + 1}: {len(batch)} items")
            except Exception as e:
                logger.error(f"Batch upsert error: {e}")
        logger.info(f"Bulk upsert complete: {added} added, {updated} updated")
        return added, updated
    def search(self, query: str, n_results: int = 20, filters: dict = None) -> List[dict]:
        """μ‹œλ§¨ν‹± 검색"""
        if not self.collection:
            return []
        try:
            where_filter = None
            if filters:
                conditions = []
                if filters.get("category") and filters["category"] != "전체":
                    conditions.append({"category": {"$eq": filters["category"]}})
                if filters.get("author"):
                    conditions.append({"author": {"$contains": filters["author"]}})
                if conditions:
                    where_filter = {"$and": conditions} if len(conditions) > 1 else conditions[0]
            results = self.collection.query(
                query_texts=[query],
                n_results=n_results,
                where=where_filter,
                include=["documents", "metadatas", "distances"]
            )
            items = []
            if results and results['ids'] and results['ids'][0]:
                for i, doc_id in enumerate(results['ids'][0]):
                    metadata = results['metadatas'][0][i] if results['metadatas'] else {}
                    distance = results['distances'][0][i] if results['distances'] else 0
                    item = {
                        "id": doc_id,
                        "similarity_score": 1 - distance,
                        **metadata
                    }
                    items.append(item)
            return items
        except Exception as e:
            logger.error(f"Search error: {e}")
            return []
    def get_all(self, limit: int = 1000) -> List[dict]:
        """전체 데이터 쑰회"""
        if not self.collection:
            return []
        try:
            results = self.collection.get(
                limit=limit,
                include=["metadatas"]
            )
            items = []
            if results and results['ids']:
                for i, doc_id in enumerate(results['ids']):
                    metadata = results['metadatas'][i] if results['metadatas'] else {}
                    items.append({"id": doc_id, **metadata})
            return items
        except Exception as e:
            logger.error(f"Get all error: {e}")
            return []
    def get_count(self) -> int:
        """총 데이터 수"""
        if not self.collection:
            return 0
        try:
            return self.collection.count()
        except:
            return 0
    def clear(self):
        """μΊμ‹œ μ΄ˆκΈ°ν™”"""
        if self.client:
            try:
                self.client.delete_collection("announcements")
                self._init_db()
                logger.info("Cache cleared")
            except Exception as e:
                logger.error(f"Clear error: {e}")
class ContentVectorCache:
    """λ³Έλ¬Έ 벑터 μΊμ‹œ (ν•œκ΅­μ–΄ μž„λ² λ”©)"""
    def __init__(self, shared_client=None):
        self.client = shared_client
        self.collection = None
        self.embedding_model = None
        self._index_status = {"in_progress": False, "current": 0, "total": 0, "failed": []}
        self._load_index_status()
    def _load_index_status(self):
        """인덱싱 μƒνƒœ λ‘œλ“œ"""
        if CONTENT_INDEX_FILE.exists():
            try:
                with open(CONTENT_INDEX_FILE, 'r', encoding='utf-8') as f:
                    saved = json.load(f)
                    self._index_status["failed"] = saved.get("failed", [])
            except:
                pass
    def _save_index_status(self):
        """인덱싱 μƒνƒœ μ €μž₯"""
        try:
            with open(CONTENT_INDEX_FILE, 'w', encoding='utf-8') as f:
                json.dump({
                    "failed": self._index_status["failed"][-100:],
                    "last_updated": datetime.now(KST).isoformat()
                }, f, ensure_ascii=False)
        except:
            pass
    def _init_db(self):
        """λ³Έλ¬Έ 벑터 DB μ΄ˆκΈ°ν™” (메타 μΊμ‹œμ™€ ν΄λΌμ΄μ–ΈνŠΈ 곡유)"""
        if not CHROMADB_AVAILABLE:
            return
        try:
            if self.client is None:
                meta_cache = get_cache()
                self.client = meta_cache.client
            if self.client is None:
                logger.error("No ChromaDB client available for content cache")
                return
            self.collection = self.client.get_or_create_collection(
                name="announcement_contents",
                metadata={"hnsw:space": "cosine"}
            )
            logger.info("Content VectorDB initialized (shared client)")
        except Exception as e:
            logger.error(f"Content VectorDB init error: {e}")
    def _get_embedding(self, text: str) -> Optional[List[float]]:
        """ν…μŠ€νŠΈ μž„λ² λ”© 생성"""
        if self.embedding_model is None:
            self.embedding_model = get_embedding_model()
        if self.embedding_model is None:
            return None
        try:
            text = text[:8000]
            embedding = self.embedding_model.encode(text, show_progress_bar=False)
            return embedding.tolist()
        except Exception as e:
            logger.error(f"Embedding error: {e}")
            return None
    def add_content(self, pblanc_id: str, title: str, content: str) -> bool:
        """λ³Έλ¬Έ μ½˜ν…μΈ  μΆ”κ°€"""
        if not self.collection:
            self._init_db()
        if not self.collection:
            return False
        try:
            embedding = self._get_embedding(content)
            if embedding is None:
                return False
            doc_id = f"content_{pblanc_id}"
            self.collection.upsert(
                ids=[doc_id],
                embeddings=[embedding],
                documents=[content[:5000]],
                metadatas=[{
                    "pblancId": pblanc_id,
                    "title": title[:200],
                    "content_preview": content[:500],
                    "indexed_at": datetime.now(KST).isoformat()
                }]
            )
            return True
        except Exception as e:
            logger.error(f"Add content error: {e}")
            return False
    def search_similar(self, query: str, n_results: int = 20) -> List[dict]:
        """μœ μ‚¬ λ³Έλ¬Έ 검색"""
        if not self.collection:
            self._init_db()
        if not self.collection:
            return []
        try:
            embedding = self._get_embedding(query)
            if embedding is None:
                return []
            results = self.collection.query(
                query_embeddings=[embedding],
                n_results=n_results,
                include=["documents", "metadatas", "distances"]
            )
            items = []
            if results and results['ids'] and results['ids'][0]:
                for i, doc_id in enumerate(results['ids'][0]):
                    metadata = results['metadatas'][0][i] if results['metadatas'] else {}
                    distance = results['distances'][0][i] if results['distances'] else 0
                    items.append({
                        "id": doc_id,
                        "similarity_score": 1 - distance,
                        "pblancId": metadata.get("pblancId", ""),
                        "title": metadata.get("title", ""),
                        "content_preview": metadata.get("content_preview", ""),
                    })
            return items
        except Exception as e:
            logger.error(f"Content search error: {e}")
            return []
    def get_indexed_ids(self) -> set:
        """μΈλ±μ‹±λœ 곡고 ID λͺ©λ‘"""
        if not self.collection:
            self._init_db()
        if not self.collection:
            return set()
        try:
            results = self.collection.get(include=["metadatas"])
            ids = set()
            if results:
                # 1. λ©”νƒ€λ°μ΄ν„°μ—μ„œ pblancId μΆ”μΆœ
                if results.get('metadatas'):
                    for meta in results['metadatas']:
                        if meta and meta.get("pblancId"):
                            ids.add(meta["pblancId"])
                # 2. doc_idμ—μ„œλ„ μΆ”μΆœ (content_XXX ν˜•μ‹)
                if results.get('ids'):
                    for doc_id in results['ids']:
                        if doc_id and doc_id.startswith("content_"):
                            pblanc_id = doc_id.replace("content_", "", 1)
                            if pblanc_id:
                                ids.add(pblanc_id)
            logger.info(f"Found {len(ids)} indexed content IDs")
            return ids
        except Exception as e:
            logger.error(f"Get indexed IDs error: {e}")
            return set()
    def get_indexed_count(self) -> int:
        """μΈλ±μ‹±λœ μ½˜ν…μΈ  수"""
        if not self.collection:
            self._init_db()
        if not self.collection:
            return 0
        try:
            return self.collection.count()
        except:
            return 0
    def get_status(self) -> dict:
        """인덱싱 μƒνƒœ"""
        return {
            "total_indexed": self.get_indexed_count(),
            "in_progress": self._index_status["in_progress"],
            "progress_current": self._index_status["current"],
            "progress_total": self._index_status["total"],
            "failed_count": len(self._index_status["failed"])
        }
class UserProfileCache:
    """μ‚¬μš©μž ν”„λ‘œν•„ μ €μž₯/λ‘œλ“œ 클래슀 (이메일 기반)"""
    def __init__(self):
        self.profiles_file = PROFILE_DIR / "profiles.json"
        self.profiles = {}
        self._load_profiles()
    def _load_profiles(self):
        """ν”„λ‘œν•„ 데이터 λ‘œλ“œ"""
        if self.profiles_file.exists():
            try:
                with open(self.profiles_file, 'r', encoding='utf-8') as f:
                    self.profiles = json.load(f)
                logger.info(f"Loaded {len(self.profiles)} user profiles")
            except Exception as e:
                logger.error(f"Profile load error: {e}")
                self.profiles = {}
    def _save_profiles(self):
        """ν”„λ‘œν•„ 데이터 μ €μž₯"""
        try:
            with open(self.profiles_file, 'w', encoding='utf-8') as f:
                json.dump(self.profiles, f, ensure_ascii=False, indent=2)
        except Exception as e:
            logger.error(f"Profile save error: {e}")
    def _normalize_email(self, email: str) -> str:
        """이메일 μ •κ·œν™” (μ†Œλ¬Έμž λ³€ν™˜, 곡백 제거)"""
        return email.strip().lower()
    def save_profile(self, email: str, profile_data: dict) -> Tuple[bool, str]:
        """ν”„λ‘œν•„ μ €μž₯"""
        if not email or '@' not in email:
            return False, "μ˜¬λ°”λ₯Έ 이메일 μ£Όμ†Œλ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”."
        email_key = self._normalize_email(email)
        self.profiles[email_key] = {
            "email": email_key,
            "profile": profile_data,
            "updated_at": datetime.now(KST).isoformat(),
            "created_at": self.profiles.get(email_key, {}).get("created_at", datetime.now(KST).isoformat())
        }
        self._save_profiles()
        logger.info(f"Profile saved for: {email_key}")
        return True, f"βœ… ν”„λ‘œν•„μ΄ μ €μž₯λ˜μ—ˆμŠ΅λ‹ˆλ‹€. ({email_key})"
    def load_profile(self, email: str) -> Tuple[Optional[dict], str]:
        """ν”„λ‘œν•„ λ‘œλ“œ"""
        if not email or '@' not in email:
            return None, "μ˜¬λ°”λ₯Έ 이메일 μ£Όμ†Œλ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”."
        email_key = self._normalize_email(email)
        if email_key in self.profiles:
            data = self.profiles[email_key]
            logger.info(f"Profile loaded for: {email_key}")
            return data.get("profile", {}), f"βœ… ν”„λ‘œν•„μ„ λΆˆλŸ¬μ™”μŠ΅λ‹ˆλ‹€. (λ§ˆμ§€λ§‰ μˆ˜μ •: {data.get('updated_at', 'μ•Œ 수 μ—†μŒ')[:10]})"
        return None, f"ℹ️ '{email_key}'에 μ €μž₯된 ν”„λ‘œν•„μ΄ μ—†μŠ΅λ‹ˆλ‹€. μƒˆλ‘œ μž…λ ₯ν•΄μ£Όμ„Έμš”."
    def delete_profile(self, email: str) -> Tuple[bool, str]:
        """ν”„λ‘œν•„ μ‚­μ œ"""
        email_key = self._normalize_email(email)
        if email_key in self.profiles:
            del self.profiles[email_key]
            self._save_profiles()
            return True, f"βœ… ν”„λ‘œν•„μ΄ μ‚­μ œλ˜μ—ˆμŠ΅λ‹ˆλ‹€. ({email_key})"
        return False, f"⚠️ μ‚­μ œν•  ν”„λ‘œν•„μ΄ μ—†μŠ΅λ‹ˆλ‹€."
    def get_profile_count(self) -> int:
        """μ €μž₯된 ν”„λ‘œν•„ 수"""
        return len(self.profiles)
_cache_instance = None
_content_cache_instance = None
_profile_cache_instance = None
_scheduler = None
def get_cache() -> AnnouncementCache:
    """메타 μΊμ‹œ 싱글톀"""
    global _cache_instance
    if _cache_instance is None:
        _cache_instance = AnnouncementCache()
    return _cache_instance
def get_content_cache() -> ContentVectorCache:
    """λ³Έλ¬Έ μΊμ‹œ 싱글톀 (메타 μΊμ‹œμ™€ ν΄λΌμ΄μ–ΈνŠΈ 곡유)"""
    global _content_cache_instance
    if _content_cache_instance is None:
        meta_cache = get_cache()
        _content_cache_instance = ContentVectorCache(shared_client=meta_cache.client)
    return _content_cache_instance
def get_profile_cache() -> UserProfileCache:
    """ν”„λ‘œν•„ μΊμ‹œ 싱글톀"""
    global _profile_cache_instance
    if _profile_cache_instance is None:
        _profile_cache_instance = UserProfileCache()
    return _profile_cache_instance
def save_sync_metadata(api_count: int, added: int, updated: int, total: int):
    """동기화 메타데이터 μ €μž₯"""
    try:
        existing = {}
        if METADATA_FILE.exists():
            with open(METADATA_FILE, 'r', encoding='utf-8') as f:
                existing = json.load(f)
        history = existing.get("sync_history", [])
        history.append({
            "timestamp": datetime.now(KST).isoformat(),
            "api_count": api_count,
            "added": added,
            "updated": updated,
            "total_cached": total
        })
        history = history[-50:]
        metadata = {
            "last_sync": datetime.now(KST).isoformat(),
            "total_count": total,
            "sync_history": history
        }
        with open(METADATA_FILE, 'w', encoding='utf-8') as f:
            json.dump(metadata, f, ensure_ascii=False, indent=2)
    except Exception as e:
        logger.error(f"Save metadata error: {e}")
def get_sync_status() -> dict:
    """동기화 μƒνƒœ 쑰회"""
    cache = get_cache()
    content_cache = get_content_cache()
    content_status = content_cache.get_status()
    status = {
        "total_count": cache.get_count(),
        "last_sync": None,
        "sync_history": [],
        "db_path": str(DB_PATH),
        "chromadb_available": CHROMADB_AVAILABLE,
        "scheduler_available": SCHEDULER_AVAILABLE,
        "content_indexed": content_status["total_indexed"],
        "content_indexing_in_progress": content_status["in_progress"],
        "content_progress": f"{content_status['progress_current']}/{content_status['progress_total']}",
        "content_failed_count": content_status["failed_count"],
        "embedding_available": EMBEDDING_AVAILABLE
    }
    if METADATA_FILE.exists():
        try:
            with open(METADATA_FILE, 'r', encoding='utf-8') as f:
                metadata = json.load(f)
                status["last_sync"] = metadata.get("last_sync")
                status["sync_history"] = metadata.get("sync_history", [])[-5:]
        except:
            pass
    return status
def sync_from_api() -> Tuple[int, int, str]:
    """APIμ—μ„œ 데이터 동기화"""
    try:
        from file_api import fetch_all_from_api
        logger.info(f"Starting sync at {datetime.now(KST).strftime('%Y-%m-%d %H:%M:%S %Z')}")
        result = fetch_all_from_api()
        # fetch_all_from_apiλŠ” (items, error_msg) νŠœν”Œ λ°˜ν™˜
        if isinstance(result, tuple):
            items, error_msg = result
            if error_msg and not items:
                return 0, 0, f"API 였λ₯˜: {error_msg}"
        else:
            items = result
        if not items:
            return 0, 0, "APIμ—μ„œ 데이터λ₯Ό κ°€μ Έμ˜€μ§€ λͺ»ν–ˆμŠ΅λ‹ˆλ‹€."
        cache = get_cache()
        added, updated = cache.bulk_upsert(items)
        total = cache.get_count()
        save_sync_metadata(len(items), added, updated, total)
        msg = f"βœ… 동기화 μ™„λ£Œ: API {len(items)}건 β†’ μ‹ κ·œ {added}건, μ—…λ°μ΄νŠΈ {updated}건 (총 {total}건)"
        logger.info(msg)
        start_background_indexing()
        return added, updated, msg
    except Exception as e:
        logger.error(f"Sync error: {e}")
        return 0, 0, f"동기화 였λ₯˜: {str(e)}"
def get_cached_announcements(category: str = "전체", region: str = "전체(μ§€μ—­)", keyword: str = "") -> Tuple[List[dict], str]:
    """μΊμ‹œμ—μ„œ 곡고 쑰회 - (items, status_msg) νŠœν”Œ λ°˜ν™˜"""
    cache = get_cache()
    if keyword:
        items = cache.search(keyword, n_results=100)
        return items, f"πŸ” '{keyword}' 검색"
    else:
        items = cache.get_all(limit=1000)
        return items, f"⚑ μΊμ‹œμ—μ„œ {len(items)}건 λ‘œλ“œ"
_indexing_thread = None
_indexing_lock = threading.Lock()
def background_index_contents():
    """λ°±κ·ΈλΌμš΄λ“œ λ³Έλ¬Έ 인덱싱"""
    content_cache = get_content_cache()
    if content_cache._index_status["in_progress"]:
        logger.info("Background indexing already running")
        return
    content_cache._index_status["in_progress"] = True
    try:
        from file_api import fetch_announcement_detail, download_file, extract_text_from_file
        cache = get_cache()
        all_items = cache.get_all(limit=2000)
        indexed_ids = content_cache.get_indexed_ids()
        def safe_str(val):
            return str(val) if val else ""
        def is_ongoing_check(req_dt: str) -> bool:
            """마감일 확인"""
            if not req_dt:
                return True
            try:
                import re
                date_patterns = [
                    r'(\d{4})[.\-/](\d{1,2})[.\-/](\d{1,2})',
                    r'(\d{4})λ…„\s*(\d{1,2})μ›”\s*(\d{1,2})일'
                ]
                dates_found = []
                for pattern in date_patterns:
                    matches = re.findall(pattern, req_dt)
                    for m in matches:
                        try:
                            d = datetime(int(m[0]), int(m[1]), int(m[2]))
                            dates_found.append(d)
                        except:
                            continue
                if dates_found:
                    end_date = max(dates_found)
                    today = datetime.now()
                    return end_date >= today
                return True
            except:
                return True
        items_to_index = []
        skipped_expired = 0
        skipped_indexed = 0
        for item in all_items:
            pblanc_id = safe_str(item.get("pblancId") or item.get("seq"))
            if not pblanc_id:
                continue
            if pblanc_id in indexed_ids:
                skipped_indexed += 1
                continue
            req_dt = safe_str(item.get("reqstDt") or item.get("reqstBeginEndDe"))
            if not is_ongoing_check(req_dt):
                skipped_expired += 1
                continue
            items_to_index.append(item)
        total = len(items_to_index)
        content_cache._index_status["total"] = total
        content_cache._index_status["current"] = 0
        logger.info(f"Starting background content indexing: {total} items (skipped {skipped_indexed} already indexed, {skipped_expired} expired)")
        for i, item in enumerate(items_to_index):
            if not content_cache._index_status["in_progress"]:
                break
            content_cache._index_status["current"] = i + 1
            pblanc_id = safe_str(item.get("pblancId") or item.get("seq"))
            title = safe_str(item.get("title") or item.get("pblancNm"))
            print_url = safe_str(item.get("printFileUrl") or item.get("printFlpthNm"))
            print_name = safe_str(item.get("printFileName") or item.get("printFileNm"))
            content_text = ""
            if print_url and print_name:
                try:
                    with tempfile.TemporaryDirectory() as tmp_dir:
                        file_path, err = download_file(print_url, tmp_dir, print_name)
                        if file_path and not err:
                            text, ext_err = extract_text_from_file(file_path)
                            if text:
                                content_text = text
                except Exception as e:
                    logger.warning(f"Text extraction failed for {pblanc_id}: {e}")
            if not content_text:
                link = safe_str(item.get("link") or item.get("pblancUrl"))
                if link:
                    try:
                        detail_content, _, scraped_print = fetch_announcement_detail(link)
                        if detail_content:
                            content_text = detail_content
                        elif scraped_print and scraped_print.get("url"):
                            with tempfile.TemporaryDirectory() as tmp_dir:
                                file_path, err = download_file(
                                    scraped_print["url"], tmp_dir,
                                    scraped_print.get("filename", "file")
                                )
                                if file_path and not err:
                                    text, _ = extract_text_from_file(file_path)
                                    if text:
                                        content_text = text
                    except Exception as e:
                        pass
            if content_text and len(content_text) > 100:
                success = content_cache.add_content(pblanc_id, title, content_text)
                if success:
                    logger.info(f"Indexed [{i+1}/{total}]: {title[:50]}...")
                else:
                    content_cache._index_status["failed"].append(pblanc_id)
            else:
                content_cache._index_status["failed"].append(pblanc_id)
            if (i + 1) % 50 == 0:
                content_cache._save_index_status()
        content_cache._save_index_status()
        logger.info(f"Background indexing complete: {content_cache.get_indexed_count()} indexed")
    except Exception as e:
        logger.error(f"Background indexing error: {e}")
    finally:
        content_cache._index_status["in_progress"] = False
def start_background_indexing() -> bool:
    """λ°±κ·ΈλΌμš΄λ“œ 인덱싱 μ‹œμž‘"""
    global _indexing_thread
    with _indexing_lock:
        if _indexing_thread and _indexing_thread.is_alive():
            logger.info("Background indexing already running")
            return False
        _indexing_thread = threading.Thread(target=background_index_contents, daemon=True)
        _indexing_thread.start()
        logger.info("Background content indexing thread started")
        return True
def stop_scheduler():
    """μŠ€μΌ€μ€„λŸ¬ 쀑지"""
    global _scheduler
    if _scheduler:
        _scheduler.shutdown()
        _scheduler = None
        logger.info("Scheduler stopped")
def start_scheduler():
    """μŠ€μΌ€μ€„λŸ¬ μ‹œμž‘"""
    global _scheduler
    if not SCHEDULER_AVAILABLE:
        logger.warning("Scheduler not available")
        return False
    if _scheduler:
        return True
    try:
        _scheduler = BackgroundScheduler(timezone=KST)
        _scheduler.add_job(
            sync_from_api,
            CronTrigger(hour=10, minute=0, timezone=KST),
            id='sync_10am',
            name='Daily sync at 10:00 KST',
            replace_existing=True
        )
        _scheduler.add_job(
            sync_from_api,
            CronTrigger(hour=22, minute=0, timezone=KST),
            id='sync_10pm',
            name='Daily sync at 22:00 KST',
            replace_existing=True
        )
        _scheduler.start()
        logger.info("Scheduler started: sync at 10:00 and 22:00 KST")
        return True
    except Exception as e:
        logger.error(f"Scheduler start error: {e}")
        return False
def manual_sync() -> str:
    """μˆ˜λ™ 동기화 μ‹€ν–‰"""
    added, updated, msg = sync_from_api()
    return msg
def initialize_cache_system():
    """μΊμ‹œ μ‹œμŠ€ν…œ μ΄ˆκΈ°ν™” (μ•± μ‹œμž‘ μ‹œ 호좜)"""
    logger.info("Initializing cache system...")
    cache = get_cache()
    count = cache.get_count()
    if count == 0:
        logger.info("Cache is empty, performing initial sync...")
        sync_from_api()
    else:
        logger.info(f"Cache loaded with {count} announcements")
    content_cache = get_content_cache()
    content_count = content_cache.get_indexed_count()
    logger.info(f"Content cache: {content_count} indexed")
    profile_cache = get_profile_cache()
    logger.info(f"Profile cache: {profile_cache.get_profile_count()} profiles")
    start_scheduler()
    start_background_indexing()
    return get_sync_status()
if __name__ == "__main__":
    print("Testing cache system...")
    status = initialize_cache_system()
    print(f"Status: {json.dumps(status, ensure_ascii=False, indent=2)}")