"""
샘플 제품 데이터 추가
"""

import sqlite3
import os
import json

def insert_sample_products():
    """실제 바코드로 샘플 제품 추가"""
    db_path = os.path.join(os.path.dirname(__file__), 'db', 'mileage.db')
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    # 샘플 제품 데이터
    products = [
        {
            "barcode": "8806436016712",
            "product_name": "탁센캡슐",
            "manufacturer": "동아제약",
            "drug_classification": "일반의약품",
            "ingredients": [
                {"name": "나프록센", "amount": "250mg", "role": "주성분"}
            ],
            "tags_symptoms": ["생리통", "치통", "골관절염", "두통", "근육통"],
            "tags_ingredients": ["나프록센 250mg", "비스테로이드성 소염진통제"],
            "tags_effects": ["진통", "소염", "해열"],
            "categories": [
                {"name": "진통소염제", "score": 1.0},
                {"name": "진통제", "score": 0.9},
                {"name": "해열제", "score": 0.3}
            ]
        },
        {
            "barcode": "8806606002231",
            "product_name": "베아제정(10정)",
            "manufacturer": "대웅제약",
            "drug_classification": "일반의약품",
            "ingredients": [
                {"name": "판크레아틴", "amount": "150mg", "role": "주성분"}
            ],
            "tags_symptoms": ["소화불량", "복부팽만", "가스"],
            "tags_ingredients": ["판크레아틴 150mg", "소화효소"],
            "tags_effects": ["소화촉진", "가스제거"],
            "categories": [
                {"name": "소화제", "score": 1.0},
                {"name": "위장약", "score": 0.8}
            ]
        },
        {
            "barcode": "8806265019618",
            "product_name": "마그비맥스",
            "manufacturer": "일양약품",
            "drug_classification": "일반의약품",
            "ingredients": [
                {"name": "메코발라민", "amount": "1mg", "role": "비타민B12"},
                {"name": "UDCA", "amount": "60mg", "role": "간기능개선"},
                {"name": "타우린", "amount": "100mg", "role": "피로회복"}
            ],
            "tags_symptoms": ["피로", "구내염", "신경통", "근육통"],
            "tags_ingredients": ["메코발라민 1mg", "UDCA 60mg", "타우린 100mg"],
            "tags_effects": ["피로회복", "간기능개선", "신경계보호"],
            "categories": [
                {"name": "복합비타민", "score": 1.0},
                {"name": "간영양제", "score": 0.9},
                {"name": "피로회복제", "score": 1.0}
            ]
        }
    ]

    try:
        for product in products:
            # 1. product_master 삽입
            cursor.execute("""
                INSERT OR REPLACE INTO product_master
                (barcode, product_name, manufacturer, drug_classification,
                 ingredients_json, tags_symptoms, tags_effects, tags_ingredients,
                 is_verified)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)
            """, (
                product["barcode"],
                product["product_name"],
                product["manufacturer"],
                product["drug_classification"],
                json.dumps(product["ingredients"], ensure_ascii=False),
                json.dumps(product["tags_symptoms"], ensure_ascii=False),
                json.dumps(product["tags_effects"], ensure_ascii=False),
                json.dumps(product["tags_ingredients"], ensure_ascii=False)
            ))

            # 2. product_category_mapping 삽입
            for cat in product["categories"]:
                cursor.execute("""
                    INSERT OR REPLACE INTO product_category_mapping
                    (barcode, category_name, relevance_score)
                    VALUES (?, ?, ?)
                """, (
                    product["barcode"],
                    cat["name"],
                    cat["score"]
                ))

        conn.commit()
        print("[OK] 샘플 제품 3개 추가 완료!")

        # 결과 확인
        cursor.execute("SELECT COUNT(*) FROM product_master")
        count = cursor.fetchone()[0]
        print(f"\n전체 제품 수: {count}개")

        print("\n추가된 제품:")
        cursor.execute("""
            SELECT barcode, product_name, drug_classification
            FROM product_master
        """)
        for row in cursor.fetchall():
            print(f"  - {row[0]}: {row[1]} ({row[2]})")

        # 카테고리 매핑 확인
        print("\n제품-카테고리 매핑:")
        cursor.execute("""
            SELECT p.product_name, m.category_name, m.relevance_score
            FROM product_master p
            JOIN product_category_mapping m ON p.barcode = m.barcode
            ORDER BY p.product_name, m.relevance_score DESC
        """)
        for row in cursor.fetchall():
            print(f"  {row[0]:20} -> {row[1]:15} (관련도: {row[2]:.1f})")

    except Exception as e:
        print(f"[ERROR] {e}")
        conn.rollback()
    finally:
        conn.close()

if __name__ == '__main__':
    insert_sample_products()
