#!/usr/bin/env python3
"""
쌍화탕 처방의 당귀를 일당귀로 수정
"""

import sqlite3

def update_danggui():
    """쌍화탕의 당귀를 일당귀로 수정"""

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

    try:
        # 현재 쌍화탕에 등록된 당귀 확인
        print("🔍 현재 쌍화탕 처방의 당귀 확인...")
        cursor.execute("""
            SELECT f.formula_name, fi.ingredient_code, hm.herb_name, fi.grams_per_cheop
            FROM formulas f
            JOIN formula_ingredients fi ON f.formula_id = fi.formula_id
            JOIN herb_masters hm ON fi.ingredient_code = hm.ingredient_code
            WHERE f.formula_name LIKE '%쌍화%'
              AND hm.herb_name LIKE '%당귀%'
        """)

        current = cursor.fetchall()
        print(f"현재 상태:")
        for name, code, herb, amount in current:
            print(f"  - {name}: {herb} ({code}) - {amount}g")

        # 당귀(3105H1AHM)를 일당귀(3403H1AHM)로 변경
        print(f"\n✏️ 당귀(3105H1AHM) → 일당귀(3403H1AHM)로 변경 중...")

        # 쌍화탕 처방 ID 확인
        cursor.execute("""
            SELECT formula_id
            FROM formulas
            WHERE formula_name LIKE '%쌍화%'
        """)

        formula_ids = [row[0] for row in cursor.fetchall()]

        if formula_ids:
            # 당귀를 일당귀로 수정
            cursor.execute("""
                UPDATE formula_ingredients
                SET ingredient_code = '3403H1AHM'
                WHERE ingredient_code = '3105H1AHM'
                  AND formula_id IN ({})
            """.format(','.join('?' * len(formula_ids))), formula_ids)

            updated_count = cursor.rowcount
            print(f"✅ {updated_count}개 항목 수정됨")

            # 변경 후 확인
            print(f"\n🔍 수정 후 확인...")
            cursor.execute("""
                SELECT f.formula_name, fi.ingredient_code, hm.herb_name, fi.grams_per_cheop
                FROM formulas f
                JOIN formula_ingredients fi ON f.formula_id = fi.formula_id
                JOIN herb_masters hm ON fi.ingredient_code = hm.ingredient_code
                WHERE f.formula_name LIKE '%쌍화%'
                  AND hm.herb_name LIKE '%당귀%'
            """)

            updated = cursor.fetchall()
            print(f"수정된 상태:")
            for name, code, herb, amount in updated:
                print(f"  - {name}: {herb} ({code}) - {amount}g")

            conn.commit()
            print(f"\n✅ 쌍화탕 당귀 수정 완료!")

            # 전체 처방 구성 확인
            print(f"\n📋 수정된 쌍화탕 전체 구성:")
            print("-"*60)

            for formula_id in formula_ids:
                cursor.execute("""
                    SELECT f.formula_name
                    FROM formulas f
                    WHERE f.formula_id = ?
                """, (formula_id,))

                formula_name = cursor.fetchone()[0]
                print(f"\n{formula_name}:")

                cursor.execute("""
                    SELECT hm.herb_name, fi.grams_per_cheop, fi.notes
                    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,))

                for herb, amount, notes in cursor.fetchall():
                    marker = "✅" if herb == "일당귀" else "  "
                    print(f"  {marker} {herb}: {amount}g ({notes if notes else ''})")
        else:
            print("❌ 쌍화탕 처방을 찾을 수 없습니다.")

    except sqlite3.Error as e:
        print(f"❌ 데이터베이스 오류: {e}")
        conn.rollback()
        return False
    finally:
        conn.close()

    return True

if __name__ == "__main__":
    print("🌿 쌍화탕 당귀 수정 프로그램")
    print("="*60)

    if update_danggui():
        print("\n✅ 수정 작업이 완료되었습니다.")
    else:
        print("\n❌ 수정 중 오류가 발생했습니다.")