#!/usr/bin/env python3
"""
settings 테이블을 올바른 스키마로 수정
현재: key, value
목표: ordinal (PK), key (NOT NULL), value_json (JSON), note, updated_at
"""

import sqlite3
import json
from pathlib import Path
from datetime import datetime

def fix_settings_schema_v2():
    """settings 테이블 스키마 수정"""

    db_path = Path('src/quant_engine/snapshot_admin.db')
    conn = sqlite3.connect(db_path)
    conn.row_factory = sqlite3.Row
    cursor = conn.cursor()

    # 현재 데이터 백업
    cursor.execute("SELECT key, value FROM settings")
    old_rows = cursor.fetchall()
    print(f"현재 settings: {len(old_rows)}개 행")

    # 기존 테이블 삭제
    cursor.execute("DROP TABLE IF EXISTS settings")

    # 올바른 스키마로 생성
    cursor.execute("""
        CREATE TABLE settings (
            ordinal INTEGER PRIMARY KEY,
            key TEXT NOT NULL,
            value_json TEXT NOT NULL,
            note TEXT DEFAULT '',
            updated_at TEXT NOT NULL
        )
    """)

    print("새 스키마 생성:")
    print("  ordinal INTEGER PRIMARY KEY")
    print("  key TEXT NOT NULL")
    print("  value_json TEXT NOT NULL")
    print("  note TEXT DEFAULT ''")
    print("  updated_at TEXT NOT NULL")

    # 데이터 복원
    timestamp = datetime.now().isoformat()

    for ordinal, row in enumerate(old_rows, start=1):
        key = row['key']
        value = row['value']

        # value를 JSON으로 변환
        try:
            value_json = json.dumps(str(value), ensure_ascii=False)
        except:
            value_json = json.dumps("", ensure_ascii=False)

        cursor.execute("""
            INSERT INTO settings (ordinal, key, value_json, note, updated_at)
            VALUES (?, ?, ?, ?, ?)
        """, (ordinal, key, value_json, "", timestamp))

    conn.commit()

    # 검증
    cursor.execute("SELECT COUNT(*) FROM settings")
    count = cursor.fetchone()[0]
    print(f"\n복원된 settings: {count}개 행")

    cursor.execute("SELECT ordinal, key, value_json FROM settings LIMIT 3")
    print("샘플 데이터:")
    for ordinal, key, value_json in cursor.fetchall():
        value = json.loads(value_json)
        print(f"  {ordinal}. {key} = {value}")

    conn.close()

    print(f"\n[OK] settings 테이블 스키마 수정 완료")

if __name__ == "__main__":
    fix_settings_schema_v2()
