#!/usr/bin/env python3
"""
formulas 테이블의 칼럼 구조 확인
"""

import sqlite3

def check_formula_structure():
    """formulas 테이블의 전체 구조 확인"""

    conn = sqlite3.connect('database/kdrug.db')
    cursor = conn.cursor()

    print("🔍 formulas 테이블 구조 확인")
    print("="*70)

    # 테이블 구조 확인
    cursor.execute("PRAGMA table_info(formulas)")
    columns = cursor.fetchall()

    print("\n📊 formulas 테이블 칼럼 목록:")
    print("-"*70)
    print(f"{'번호':>4} | {'칼럼명':20} | {'타입':15} | {'NULL 허용':10} | {'기본값'}")
    print("-"*70)

    efficacy_columns = []
    for col in columns:
        cid, name, type_name, notnull, dflt_value, pk = col
        null_str = "NOT NULL" if notnull else "NULL"
        default_str = dflt_value if dflt_value else "-"

        print(f"{cid:4d} | {name:20} | {type_name:15} | {null_str:10} | {default_str}")

        # 효능 관련 칼럼 찾기
        if 'efficacy' in name.lower() or 'indication' in name.lower() or '효능' in name:
            efficacy_columns.append(name)

    print("\n" + "="*70)

    if efficacy_columns:
        print(f"✅ 효능 관련 칼럼 발견: {', '.join(efficacy_columns)}")
    else:
        print("❌ 효능 관련 칼럼이 없습니다.")

    # 실제 데이터 예시 확인
    print("\n📋 십전대보탕 데이터 예시:")
    print("-"*70)

    cursor.execute("""
        SELECT * FROM formulas
        WHERE formula_code = 'SJDB01'
    """)

    row = cursor.fetchone()
    if row:
        col_names = [description[0] for description in cursor.description]
        for i, (col_name, value) in enumerate(zip(col_names, row)):
            if value and value != 0:  # 값이 있는 경우만 표시
                print(f"{col_name:25}: {str(value)[:100]}")

    # prescription_details 테이블도 확인
    print("\n\n🔍 prescription_details 테이블 확인 (혹시 여기 있는지)")
    print("="*70)

    cursor.execute("""
        SELECT name FROM sqlite_master
        WHERE type='table' AND name='prescription_details'
    """)

    if cursor.fetchone():
        cursor.execute("PRAGMA table_info(prescription_details)")
        columns = cursor.fetchall()

        print("📊 prescription_details 테이블 칼럼:")
        print("-"*70)

        for col in columns:
            cid, name, type_name, notnull, dflt_value, pk = col
            if 'efficacy' in name.lower() or 'indication' in name.lower():
                print(f"  ✅ {name}: {type_name}")

    # formula_details 테이블도 확인
    print("\n\n🔍 formula_details 테이블 확인")
    print("="*70)

    cursor.execute("""
        SELECT name FROM sqlite_master
        WHERE type='table' AND name='formula_details'
    """)

    if cursor.fetchone():
        cursor.execute("PRAGMA table_info(formula_details)")
        columns = cursor.fetchall()

        print("📊 formula_details 테이블 칼럼:")
        print("-"*70)

        for col in columns:
            cid, name, type_name, notnull, dflt_value, pk = col
            print(f"  {name}: {type_name}")

        # 실제 데이터 확인
        cursor.execute("""
            SELECT * FROM formula_details
            WHERE formula_id = (SELECT formula_id FROM formulas WHERE formula_code = 'SJDB01')
        """)

        row = cursor.fetchone()
        if row:
            print("\n십전대보탕 상세 정보:")
            col_names = [description[0] for description in cursor.description]
            for col_name, value in zip(col_names, row):
                if value:
                    print(f"  {col_name}: {str(value)[:100]}")
    else:
        print("❌ formula_details 테이블이 없습니다.")

    conn.close()

if __name__ == "__main__":
    check_formula_structure()