#!/usr/bin/env python3
"""
삼소음 처방 데이터 검증 스크립트
"""

import sqlite3

def verify_samsoeun():
    """추가된 삼소음 처방 검증"""

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

    print("🔍 삼소음 처방 상세 검증")
    print("="*70)

    # 삼소음 처방 정보 조회
    cursor.execute("""
        SELECT f.formula_id, f.formula_code, f.formula_name, f.description,
               f.base_cheop, f.base_pouches
        FROM formulas f
        WHERE f.formula_code = 'SSE001'
    """)

    formula = cursor.fetchone()

    if formula:
        formula_id, code, name, description, base_cheop, base_pouches = formula

        print(f"\n📝 {name} ({code})")
        print(f"   ID: {formula_id}")
        print(f"   설명: {description}")
        print(f"   기본 첩수: {base_cheop}첩")
        print(f"   기본 포수: {base_pouches}포")

        # 약재 구성 상세 조회
        print(f"\n   약재 구성 (1첩 기준):")
        print("   " + "-"*60)

        cursor.execute("""
            SELECT hm.herb_name, fi.grams_per_cheop, fi.notes, hm.ingredient_code
            FROM formula_ingredients fi
            JOIN herb_masters hm ON fi.ingredient_code = hm.ingredient_code
            WHERE fi.formula_id = ?
            ORDER BY fi.sort_order
        """, (formula_id,))

        ingredients = cursor.fetchall()
        total_1cheop = 0
        total_20cheop = 0  # 20첩(1제) 기준

        print(f"   {'약재명':15s} | {'1첩(g)':>8s} | {'20첩(g)':>8s} | {'효능'}")
        print("   " + "-"*60)

        for herb_name, grams, notes, code in ingredients:
            total_1cheop += grams
            grams_20 = grams * 20
            total_20cheop += grams_20
            print(f"   {herb_name:15s} | {grams:8.1f} | {grams_20:8.1f} | {notes}")

        print("   " + "-"*60)
        print(f"   {'총 용량':15s} | {total_1cheop:8.1f} | {total_20cheop:8.1f} |")

        # 원본 데이터와 비교
        print(f"\n📊 원본 데이터와 비교:")
        print("   " + "-"*60)

        original_data = {
            "인삼": (4, 80),
            "소엽": (4, 80),
            "전호": (4, 80),
            "반하": (4, 80),
            "갈근": (4, 80),
            "적복령": (4, 80),
            "대조": (4, 80),
            "진피": (3, 60),
            "길경": (3, 60),
            "지각": (3, 60),
            "감초": (3, 60),
            "건강": (1, 20)
        }

        print(f"   {'약재':10s} | {'원본 1첩':>10s} | {'DB 1첩':>10s} | {'일치여부'}")
        print("   " + "-"*60)

        # DB 데이터를 딕셔너리로 변환
        db_data = {}
        for herb_name, grams, notes, code in ingredients:
            # 약재명 정규화
            if "자소엽" in herb_name:
                key = "소엽"
            elif "복령" in herb_name:
                key = "적복령"
            elif "대추" in herb_name:
                key = "대조"
            elif "진피" in herb_name:
                key = "진피"
            else:
                key = herb_name

            db_data[key] = grams

        # 비교
        all_match = True
        for herb, (orig_1, orig_20) in original_data.items():
            db_amount = db_data.get(herb, 0)
            match = "✅" if abs(orig_1 - db_amount) < 0.01 else "❌"
            if match == "❌":
                all_match = False
            print(f"   {herb:10s} | {orig_1:10.1f}g | {db_amount:10.1f}g | {match}")

        print("\n" + "="*70)
        if all_match:
            print("✅ 모든 약재가 원본 데이터와 일치합니다!")
        else:
            print("⚠️ 일부 약재가 원본 데이터와 일치하지 않습니다.")

    else:
        print("❌ 삼소음 처방을 찾을 수 없습니다.")

    conn.close()

if __name__ == "__main__":
    verify_samsoeun()