#!/usr/bin/env python3
"""
build_ui_state 함수의 각 단계 테스트 - 직접 호출
"""

import sys
sys.path.insert(0, '.')

# Store 함수들을 직접 import
from pathlib import Path
import sqlite3
import time
import json

def test_each_function():
    """각 함수를 개별 테스트"""

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

    print("="*80)
    print("Database 함수 단계별 테스트")
    print("="*80)

    # 1. 테이블 존재 확인
    print("\n[테이블 확인]")
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    cursor.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
    tables = [row[0] for row in cursor.fetchall()]
    print(f"  테이블 수: {len(tables)}")
    print(f"  주요 테이블: settings, account_snapshot, workspace_approval_v2")

    # 각 테이블의 행 수
    for table in ['settings', 'account_snapshot', 'workspace_approval_v2', 'workspace_change_log']:
        cursor.execute(f"SELECT COUNT(*) FROM {table}")
        count = cursor.fetchone()[0]
        print(f"    {table}: {count} rows")

    # 2. settings SELECT 테스트
    print("\n[settings SELECT 테스트]")
    try:
        cursor.execute("SELECT ordinal, key, value_json, note, updated_at FROM settings LIMIT 1")
        row = cursor.fetchone()
        if row:
            print(f"  [OK] {len(row)} 컬럼: {row}")
        else:
            print(f"  [OK] 데이터 없음")
    except Exception as e:
        print(f"  [ERROR] {e}")

    # 3. account_snapshot SELECT 테스트
    print("\n[account_snapshot SELECT 테스트]")
    try:
        cursor.execute("SELECT ordinal, row_json, captured_at, account, account_type, ticker, name, parse_status, user_confirmed, updated_at FROM account_snapshot LIMIT 1")
        row = cursor.fetchone()
        if row:
            print(f"  [OK] {len(row)} 컬럼")
        else:
            print(f"  [OK] 데이터 없음")
    except Exception as e:
        print(f"  [ERROR] {e}")

    # 4. workspace_approval_v2 SELECT 테스트
    print("\n[workspace_approval_v2 SELECT 테스트]")
    try:
        cursor.execute("SELECT domain, target_ref, status, approved_by, approved_at, note, updated_at FROM workspace_approval_v2 LIMIT 1")
        row = cursor.fetchone()
        if row:
            print(f"  [OK] {len(row)} 컬럼")
        else:
            print(f"  [OK] 데이터 없음")
    except Exception as e:
        print(f"  [ERROR] {e}")

    # 5. workspace_change_log SELECT 테스트
    print("\n[workspace_change_log SELECT 테스트]")
    try:
        cursor.execute("SELECT id, domain, action, target_ref, actor, note, before_json, after_json, created_at FROM workspace_change_log LIMIT 1")
        row = cursor.fetchone()
        if row:
            print(f"  [OK] {len(row)} 컬럼")
        else:
            print(f"  [OK] 데이터 없음")
    except Exception as e:
        print(f"  [ERROR] {e}")

    conn.close()

    print("\n[완료]")

if __name__ == "__main__":
    test_each_function()
