#!/usr/bin/env python3
"""
데이터베이스 경로 자동 업데이트

레거시 경로 (outputs/) → 정규 경로 (src/quant_engine/)
"""

import re
from pathlib import Path

# 업데이트 규칙
REPLACEMENTS = [
    # KIS data collection DB
    (r'ROOT\s*\/\s*"outputs"\s*\/\s*"kis_data_collection"',
     'ROOT / "src" / "quant_engine"'),

    (r'"outputs"\s*\/\s*"kis_data_collection"\s*\/\s*"kis_data_collection\.db"',
     '"src" / "quant_engine" / "kis_data_collection.db"'),

    (r'ROOT\s*\/\s*"outputs"\s*\/\s*"snapshot_admin"\s*\/\s*"snapshot_admin\.db"',
     'ROOT / "src" / "quant_engine" / "snapshot_admin.db"'),

    # snapshot_admin DB
    (r'"outputs"\s*\/\s*"snapshot_admin"\s*\/\s*"snapshot_admin\.db"',
     '"src" / "quant_engine" / "snapshot_admin.db"'),
]

FILES_TO_UPDATE = [
    "src/quant_engine/kis_api_client_v1.py",
    "src/quant_engine/kis_data_collection_v1.py",
    "src/quant_engine/snapshot_admin_server_v1.py",
    "src/quant_engine/snapshot_admin_store_v1.py",
    "tools/run_snapshot_admin_server_v1.py",
]

def update_file(file_path: Path) -> dict:
    """파일 업데이트"""
    if not file_path.exists():
        return {"status": "NOT_FOUND", "file": str(file_path)}

    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()

    original = content
    changes = []

    # 패턴 적용
    for pattern, replacement in REPLACEMENTS:
        matches = re.findall(pattern, content)
        if matches:
            content = re.sub(pattern, replacement, content)
            changes.extend(matches)

    # 특별 처리: KIS_COLLECTION_DB 변수
    kis_pattern = r'KIS_COLLECTION_DB\s*=\s*ROOT\s*\/\s*"outputs"[^=]*$'
    if re.search(kis_pattern, content, re.MULTILINE):
        content = re.sub(
            kis_pattern,
            'KIS_COLLECTION_DB = ROOT / "src" / "quant_engine" / "kis_data_collection.db"',
            content,
            flags=re.MULTILINE
        )
        changes.append("KIS_COLLECTION_DB assignment")

    # 특별 처리: DEFAULT_DB 변수
    db_pattern = r'DEFAULT_DB\s*=\s*ROOT\s*\/\s*"outputs"[^=]*$'
    if re.search(db_pattern, content, re.MULTILINE):
        content = re.sub(
            db_pattern,
            'DEFAULT_DB = ROOT / "src" / "quant_engine" / "snapshot_admin.db"',
            content,
            flags=re.MULTILINE
        )
        changes.append("DEFAULT_DB assignment")

    if content != original:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        return {
            "status": "UPDATED",
            "file": str(file_path),
            "changes": len(set(changes))
        }
    else:
        return {
            "status": "NO_CHANGES",
            "file": str(file_path)
        }

def main():
    print("="*80)
    print("데이터베이스 경로 자동 업데이트")
    print("="*80)
    print(f"작업: outputs/* → src/quant_engine/\n")

    results = []
    for file_path_str in FILES_TO_UPDATE:
        file_path = Path(file_path_str)
        result = update_file(file_path)
        results.append(result)

        status = result["status"]
        symbol = "[OK]" if status == "UPDATED" else "[~]" if status == "NO_CHANGES" else "[!]"
        print(f"{symbol} {file_path.name}: {status}")
        if status == "UPDATED":
            print(f"      └─ {result['changes']} references updated")

    print("\n" + "="*80)
    updated = sum(1 for r in results if r["status"] == "UPDATED")
    print(f"[결과] {updated}개 파일 업데이트 완료")
    print("\n[다음 단계]")
    print("1. git diff 로 변경 내용 검토")
    print("2. git add -u && git commit")
    print("3. 배포 전 테스트 (run_snapshot_admin_server_v1.py)")

if __name__ == "__main__":
    main()
