#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
누락된 약재 추가 스크립트
"""

import sqlite3

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

    try:
        # 누락된 약재 추가
        missing_herbs = [
            ('A001100', '당귀', '보혈'),  # 보혈약
            ('A001200', '백작약', '보혈'),  # 보혈약
            ('A001300', '인삼', '대보원기'),  # 대보원기약
            ('A001400', '생강', '온중'),  # 온중약
        ]

        print("=== 누락된 약재 추가 ===")
        for code, name, efficacy in missing_herbs:
            # 약재가 이미 있는지 확인
            cursor.execute("SELECT herb_item_id FROM herb_items WHERE herb_name = ?", (name,))
            if cursor.fetchone():
                print(f"  ⚠️  {name} - 이미 존재함")
                continue

            # 약재 추가
            cursor.execute("""
                INSERT INTO herb_items (insurance_code, herb_name, specification, default_unit, is_active)
                VALUES (?, ?, ?, 'g', 1)
            """, (code, name, ''))

            herb_id = cursor.lastrowid
            print(f"  ✅ {name} (ID: {herb_id}) 추가 완료")

            # 효능 태그 연결
            cursor.execute("SELECT tag_id FROM herb_efficacy_tags WHERE tag_name = ?", (efficacy,))
            tag_result = cursor.fetchone()

            if tag_result:
                tag_id = tag_result[0]
                cursor.execute("""
                    INSERT OR IGNORE INTO herb_item_tags (herb_item_id, tag_id)
                    VALUES (?, ?)
                """, (herb_id, tag_id))
                print(f"     → 효능 '{efficacy}' 연결")

        conn.commit()

        # 쌍화탕 처방 재구성 시도
        print("\n=== 쌍화탕 처방 재구성 ===")

        # 쌍화탕 처방 ID 가져오기
        cursor.execute("SELECT formula_id FROM formulas WHERE formula_name = '쌍화탕'")
        formula_result = cursor.fetchone()

        if formula_result:
            formula_id = formula_result[0]

            # 현재 없는 약재들 다시 추가 시도
            missing_ingredients = [
                ('당귀', 6.0, '보혈'),
                ('백작약', 6.0, '보혈'),
                ('인삼', 4.0, '대보원기'),
                ('생강', 5.0, '온중'),
            ]

            for herb_name, grams, notes in missing_ingredients:
                # 이미 등록되었는지 확인
                cursor.execute("""
                    SELECT fi.ingredient_id
                    FROM formula_ingredients fi
                    JOIN herb_items h ON fi.herb_item_id = h.herb_item_id
                    WHERE fi.formula_id = ? AND h.herb_name = ?
                """, (formula_id, herb_name))

                if cursor.fetchone():
                    print(f"  ⚠️  {herb_name} - 이미 처방에 포함됨")
                    continue

                # 약재 ID 찾기
                cursor.execute("SELECT herb_item_id FROM herb_items WHERE herb_name = ?", (herb_name,))
                herb_result = cursor.fetchone()

                if herb_result:
                    herb_id = herb_result[0]
                    cursor.execute("""
                        INSERT INTO formula_ingredients (
                            formula_id, herb_item_id, grams_per_cheop, notes
                        ) VALUES (?, ?, ?, ?)
                    """, (formula_id, herb_id, grams, notes))
                    print(f"  ✅ {herb_name}: {grams}g ({notes}) 추가")

        conn.commit()

        # 최종 쌍화탕 구성 확인
        print("\n=== 최종 쌍화탕 구성 확인 ===")
        cursor.execute("""
            SELECT
                h.herb_name,
                fi.grams_per_cheop,
                fi.notes,
                GROUP_CONCAT(et.tag_name) as efficacy_tags
            FROM formula_ingredients fi
            JOIN herb_items h ON fi.herb_item_id = h.herb_item_id
            LEFT JOIN herb_item_tags hit ON h.herb_item_id = hit.herb_item_id
            LEFT JOIN herb_efficacy_tags et ON hit.tag_id = et.tag_id
            WHERE fi.formula_id = (SELECT formula_id FROM formulas WHERE formula_name = '쌍화탕')
            GROUP BY h.herb_name, fi.grams_per_cheop, fi.notes
            ORDER BY fi.grams_per_cheop DESC
        """)

        total_grams = 0
        for herb_name, grams, notes, tags in cursor.fetchall():
            total_grams += grams
            tags_display = f" [{tags}]" if tags else ""
            print(f"  - {herb_name}: {grams}g ({notes}){tags_display}")

        print(f"\n  📊 총 {cursor.rowcount}종 약재")
        print(f"  💊 1첩 총량: {total_grams}g")
        print(f"  📦 20첩 총량: {total_grams * 20}g")

        print("\n✅ 약재 추가 및 처방 재구성 완료!")

    except Exception as e:
        print(f"❌ 오류 발생: {e}")
        conn.rollback()
    finally:
        conn.close()

if __name__ == "__main__":
    add_missing_herbs()