#!/usr/bin/env python3
"""
데이터베이스 초기화 도구
data_feed, performance, positions 테이블 생성
"""

import sqlite3
from pathlib import Path
from datetime import datetime

DB_PATH = "src/quant_engine/data_feed.db"

def create_tables():
    """필수 테이블 생성"""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()

    # data_feed 테이블
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS data_feed (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            ticker TEXT NOT NULL,
            name TEXT,
            close_price REAL,
            entry_price REAL,
            quantity INTEGER,
            stop_price REAL,
            target_price REAL,
            entry_stage TEXT,
            account TEXT,
            entry_date TEXT,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            velocity_1d REAL,
            velocity_5d REAL,
            ma20 REAL,
            atr20 REAL,
            rsi_14 REAL,
            volume INTEGER,
            avg_trade_value_5d REAL,
            sector TEXT,
            beta REAL,
            UNIQUE(ticker, entry_date)
        )
    """)

    # performance 테이블
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS performance (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            ticker TEXT NOT NULL,
            name TEXT,
            entry_date TEXT NOT NULL,
            entry_price REAL NOT NULL,
            quantity INTEGER,
            stop_price REAL,
            target_price REAL,
            exit_date TEXT,
            current_price REAL,
            pnl_pct REAL,
            status TEXT,
            t20_milestone TEXT,
            entry_stage TEXT,
            account TEXT,
            recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            UNIQUE(ticker, entry_date)
        )
    """)

    # positions 테이블
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS positions (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            ticker TEXT NOT NULL UNIQUE,
            name TEXT,
            quantity INTEGER,
            entry_price REAL,
            current_price REAL,
            average_cost REAL,
            sector TEXT,
            weight_pct REAL,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    """)

    # 인덱스 생성
    cursor.execute("CREATE INDEX IF NOT EXISTS idx_data_feed_ticker ON data_feed(ticker)")
    cursor.execute("CREATE INDEX IF NOT EXISTS idx_data_feed_entry_date ON data_feed(entry_date)")
    cursor.execute("CREATE INDEX IF NOT EXISTS idx_performance_ticker ON performance(ticker)")
    cursor.execute("CREATE INDEX IF NOT EXISTS idx_performance_entry_date ON performance(entry_date)")
    cursor.execute("CREATE INDEX IF NOT EXISTS idx_positions_ticker ON positions(ticker)")

    conn.commit()
    conn.close()

    print(f"[OK] 데이터베이스 초기화 완료: {DB_PATH}")
    print(f"     생성된 테이블: data_feed, performance, positions")

def verify_database():
    """데이터베이스 검증"""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()

    # 테이블 확인
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
    tables = [row[0] for row in cursor.fetchall()]

    print(f"\n[검증] 테이블 목록: {', '.join(tables)}")
    print(f"[검증] 파일 크기: {Path(DB_PATH).stat().st_size / 1024:.2f} KB")

    # 각 테이블 구조 확인
    for table in tables:
        cursor.execute(f"PRAGMA table_info({table})")
        columns = cursor.fetchall()
        print(f"\n{table} 컬럼:")
        for col in columns:
            print(f"  - {col[1]} ({col[2]})")

    conn.close()

if __name__ == "__main__":
    # 기존 DB 백업
    db_file = Path(DB_PATH)
    if db_file.exists():
        backup_path = f"{DB_PATH}.backup.{datetime.now().strftime('%Y%m%d_%H%M%S')}"
        db_file.rename(backup_path)
        print(f"[OK] 기존 데이터베이스 백업: {backup_path}")

    # 새 DB 생성
    create_tables()

    # 검증
    verify_database()

    print("\n[완료] 데이터베이스 초기화 완료!")
