#!/usr/bin/env python3
"""
settings를 dict → list로 변환해서 로드
"""

import json
import sqlite3
from pathlib import Path

def load_settings_to_db():
    """settings를 DB에 로드"""

    # JSON에서 settings 로드
    with open('GatherTradingData.json', encoding='utf-8') as f:
        data = json.load(f)

    settings_dict = data['data']['settings']
    print(f"settings 타입: {type(settings_dict)}")
    print(f"settings 항목: {len(settings_dict)}")

    # dict → list로 변환
    settings_list = []
    for ordinal, (key, value) in enumerate(settings_dict.items(), start=1):
        settings_list.append({
            "ordinal": ordinal,
            "key": key,
            "value": value,
            "note": ""
        })

    print(f"\n변환된 settings list: {len(settings_list)} 행")
    print(f"첫 항목: {settings_list[0]}")

    # DB에 로드
    db_path = Path('src/quant_engine/snapshot_admin.db')
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

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

    # 테이블 생성
    cursor.execute("""
        CREATE TABLE settings (
            ordinal INTEGER,
            key TEXT,
            value TEXT,
            note TEXT
        )
    """)

    # 데이터 삽입
    for row in settings_list:
        cursor.execute(
            "INSERT INTO settings (ordinal, key, value, note) VALUES (?, ?, ?, ?)",
            (row['ordinal'], row['key'], row['value'], row['note'])
        )

    conn.commit()

    # 검증
    cursor.execute("SELECT COUNT(*) FROM settings")
    count = cursor.fetchone()[0]
    print(f"\n[OK] settings 로드 완료: {count} rows")

    # 샘플 보기
    cursor.execute("SELECT * FROM settings LIMIT 5")
    for row in cursor.fetchall():
        print(f"  {row}")

    conn.close()

if __name__ == "__main__":
    load_settings_to_db()
