#!/usr/bin/env python3
"""
/api/settings/save 500 에러 진단
replace_settings 함수 직접 테스트
"""

import sys
sys.path.insert(0, 'src/quant_engine')

from snapshot_admin_store_v1 import (
    open_connection,
    replace_settings,
    load_settings_rows,
    validate_settings_rows,
)
from pathlib import Path

def diagnose_settings_save():
    """Settings 저장 함수 직접 테스트"""

    db_path = Path('src/quant_engine/snapshot_admin.db')

    print("="*80)
    print("Settings 저장 함수 진단")
    print("="*80)

    # 테스트 데이터
    test_rows = [
        {
            "ordinal": 5,
            "key": "total_asset_krw",
            "value": "450000000",
            "note": "테스트 수정"
        }
    ]

    print("\n[1단계] 검증 테스트")
    try:
        errors = validate_settings_rows(test_rows)
        if errors:
            print(f"  [FAIL] 검증 오류: {errors}")
            return
        print(f"  [OK] 검증 통과")
    except Exception as e:
        print(f"  [ERROR] 검증 함수 실패: {e}")
        return

    print("\n[2단계] replace_settings 함수 테스트")
    try:
        with open_connection(db_path) as conn:
            replace_settings(conn, test_rows)
        print(f"  [OK] replace_settings 성공")
    except Exception as e:
        print(f"  [FAIL] replace_settings 오류")
        print(f"  오류 타입: {type(e).__name__}")
        print(f"  오류 메시지: {e}")
        import traceback
        traceback.print_exc()
        return

    print("\n[3단계] 저장 결과 확인")
    try:
        with open_connection(db_path) as conn:
            rows = load_settings_rows_from_conn(conn)
            for row in rows:
                if row['key'] == 'total_asset_krw':
                    print(f"  [OK] {row['key']} = {row['value']}")
    except Exception as e:
        print(f"  [ERROR] 조회 실패: {e}")

    print("\n[완료] 진단 끝")

# Helper 함수
def load_settings_rows_from_conn(conn):
    """직접 로드"""
    import sqlite3
    import json

    rows = conn.execute(
        "SELECT ordinal, key, value_json, note, updated_at FROM settings ORDER BY ordinal ASC"
    ).fetchall()

    return [
        {
            "ordinal": int(row[0]),
            "key": row[1],
            "value": json.loads(row[2]),
            "note": row[3],
            "updated_at": row[4],
        }
        for row in rows
    ]

if __name__ == "__main__":
    diagnose_settings_save()
