#!/usr/bin/env python3
"""
월비탕 처방의 진피초를 진피(陳皮)로 수정
"""

import sqlite3

def update_jinpi():
    """진피초를 진피로 수정"""

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

    try:
        # 현재 진피초로 등록된 월비탕 처방 확인
        print("🔍 현재 월비탕 처방에 등록된 진피 확인...")
        cursor.execute("""
            SELECT f.formula_name, fi.ingredient_code, hm.herb_name
            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_code LIKE 'WBT%'
              AND hm.herb_name LIKE '%진피%'
            ORDER BY f.formula_code
        """)

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

        # 진피초(3632H1AHM)를 진피(陳皮)(3466H1AHM)로 변경
        print(f"\n✏️ 진피초(3632H1AHM) → 진피(陳皮)(3466H1AHM)로 변경 중...")

        cursor.execute("""
            UPDATE formula_ingredients
            SET ingredient_code = '3466H1AHM'
            WHERE ingredient_code = '3632H1AHM'
              AND formula_id IN (
                  SELECT formula_id
                  FROM formulas
                  WHERE formula_code LIKE 'WBT%'
              )
        """)

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

        # 변경 후 확인
        print(f"\n🔍 수정 후 확인...")
        cursor.execute("""
            SELECT f.formula_name, fi.ingredient_code, hm.herb_name
            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_code LIKE 'WBT%'
              AND hm.herb_name LIKE '%진피%'
            ORDER BY f.formula_code
        """)

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

        conn.commit()
        print(f"\n✅ 진피 수정 완료!")

    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_jinpi():
        print("\n✅ 수정 작업이 완료되었습니다.")
    else:
        print("\n❌ 수정 중 오류가 발생했습니다.")