#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
데이터베이스 구조 정확히 분석
"""

import sqlite3

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

    print("=" * 80)
    print("데이터베이스 구조 완전 분석")
    print("=" * 80)

    # 1. herb_items 분석
    print("\n1. herb_items 테이블 (재고 관리):")
    cursor.execute("SELECT COUNT(*) FROM herb_items")
    count = cursor.fetchone()[0]
    print(f"   - 레코드 수: {count}")

    cursor.execute("""
        SELECT herb_item_id, insurance_code, herb_name, ingredient_code
        FROM herb_items
        WHERE herb_item_id IN (1, 2, 3)
        ORDER BY herb_item_id
    """)
    print("   - 샘플 데이터:")
    for row in cursor.fetchall():
        print(f"     ID={row[0]}: {row[2]} (보험코드: {row[1]}, 성분코드: {row[3]})")

    # 2. herb_masters 분석
    print("\n2. herb_masters 테이블 (성분코드 마스터):")
    cursor.execute("SELECT COUNT(*) FROM herb_masters")
    count = cursor.fetchone()[0]
    print(f"   - 레코드 수: {count}")

    cursor.execute("""
        SELECT ingredient_code, herb_name
        FROM herb_masters
        WHERE herb_name IN ('인삼', '감초', '당귀')
    """)
    print("   - 주요 약재:")
    for row in cursor.fetchall():
        print(f"     {row[0]}: {row[1]}")

    # 3. herb_master_extended 분석
    print("\n3. herb_master_extended 테이블 (확장 정보):")
    cursor.execute("SELECT COUNT(*) FROM herb_master_extended")
    count = cursor.fetchone()[0]
    print(f"   - 레코드 수: {count}")

    cursor.execute("""
        SELECT herb_id, ingredient_code, name_korean
        FROM herb_master_extended
        WHERE name_korean IN ('인삼', '감초', '당귀')
    """)
    print("   - 주요 약재 herb_id:")
    for row in cursor.fetchall():
        print(f"     herb_id={row[0]}: {row[2]} (성분코드: {row[1]})")

    # 4. 관계 매핑 확인
    print("\n4. 테이블 간 관계:")
    print("   herb_items.ingredient_code → herb_masters.ingredient_code")
    print("   herb_masters.ingredient_code → herb_master_extended.ingredient_code")
    print("   herb_master_extended.herb_id → herb_item_tags.herb_id")

    # 5. 올바른 JOIN 경로 제시
    print("\n5. 올바른 JOIN 방법:")
    print("""
   방법 1: herb_items에서 시작 (재고 있는 약재만)
   -----------------------------------------------
   FROM herb_items hi
   LEFT JOIN herb_masters hm ON hi.ingredient_code = hm.ingredient_code
   LEFT JOIN herb_master_extended hme ON hm.ingredient_code = hme.ingredient_code
   LEFT JOIN herb_item_tags hit ON hme.herb_id = hit.herb_id
   LEFT JOIN herb_efficacy_tags het ON hit.tag_id = het.tag_id

   방법 2: herb_masters에서 시작 (모든 약재)
   -----------------------------------------------
   FROM herb_masters hm
   LEFT JOIN herb_master_extended hme ON hm.ingredient_code = hme.ingredient_code
   LEFT JOIN herb_item_tags hit ON hme.herb_id = hit.herb_id
   LEFT JOIN herb_efficacy_tags het ON hit.tag_id = het.tag_id
   LEFT JOIN (재고 서브쿼리) inv ON hm.ingredient_code = inv.ingredient_code
   """)

    # 6. 실제 JOIN 테스트
    print("\n6. JOIN 테스트 (인삼 예시):")
    cursor.execute("""
        SELECT
            hi.herb_item_id,
            hi.herb_name as item_name,
            hi.ingredient_code,
            hme.herb_id as master_herb_id,
            hme.name_korean as master_name,
            GROUP_CONCAT(het.tag_name) as tags
        FROM herb_items hi
        LEFT JOIN herb_masters hm ON hi.ingredient_code = hm.ingredient_code
        LEFT JOIN herb_master_extended hme ON hm.ingredient_code = hme.ingredient_code
        LEFT JOIN herb_item_tags hit ON hme.herb_id = hit.herb_id
        LEFT JOIN herb_efficacy_tags het ON hit.tag_id = het.tag_id
        WHERE hi.ingredient_code = '3400H1AHM'
        GROUP BY hi.herb_item_id
    """)

    result = cursor.fetchone()
    if result:
        print(f"   herb_item_id: {result[0]}")
        print(f"   약재명: {result[1]}")
        print(f"   성분코드: {result[2]}")
        print(f"   master_herb_id: {result[3]}")
        print(f"   master 약재명: {result[4]}")
        print(f"   효능 태그: {result[5]}")

    conn.close()

if __name__ == "__main__":
    analyze_structure()