#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
API 함수 직접 테스트
"""

import os
import sqlite3

# Flask 앱과 동일한 설정
DATABASE = 'database/kdrug.db'

def get_inventory_summary():
    """app.py의 get_inventory_summary 함수와 동일"""
    conn = sqlite3.connect(DATABASE)
    conn.row_factory = sqlite3.Row
    cursor = conn.cursor()

    cursor.execute("""
        SELECT
            h.herb_item_id,
            h.insurance_code,
            h.herb_name,
            COALESCE(SUM(il.quantity_onhand), 0) as total_quantity,
            COUNT(DISTINCT il.lot_id) as lot_count,
            COUNT(DISTINCT il.origin_country) as origin_count,
            AVG(il.unit_price_per_g) as avg_price,
            MIN(il.unit_price_per_g) as min_price,
            MAX(il.unit_price_per_g) as max_price,
            COALESCE(SUM(il.quantity_onhand * il.unit_price_per_g), 0) as total_value,
            GROUP_CONCAT(DISTINCT et.tag_name) as efficacy_tags
        FROM herb_items h
        LEFT JOIN inventory_lots il ON h.herb_item_id = il.herb_item_id AND il.is_depleted = 0
        LEFT JOIN herb_products hp ON h.insurance_code = hp.product_code
        LEFT JOIN herb_item_tags hit ON COALESCE(h.ingredient_code, hp.ingredient_code) = hit.ingredient_code
        LEFT JOIN herb_efficacy_tags et ON hit.tag_id = et.tag_id
        GROUP BY h.herb_item_id, h.insurance_code, h.herb_name
        HAVING total_quantity > 0
        ORDER BY h.herb_name
    """)

    inventory = []
    for row in cursor.fetchall():
        item = dict(row)
        if item['efficacy_tags']:
            item['efficacy_tags'] = item['efficacy_tags'].split(',')
        else:
            item['efficacy_tags'] = []
        inventory.append(item)

    # 전체 요약
    total_value = sum(item['total_value'] for item in inventory)
    total_items = len(inventory)

    print("=" * 60)
    print("API 함수 직접 실행 결과")
    print("=" * 60)
    print()
    print(f"총 약재 수: {total_items}개")
    print(f"총 재고 자산: ₩{total_value:,.0f}")
    print()

    # 상세 내역
    print("약재별 재고 가치 (상위 10개):")
    print("-" * 40)
    sorted_items = sorted(inventory, key=lambda x: x['total_value'], reverse=True)
    for i, item in enumerate(sorted_items[:10], 1):
        print(f"{i:2}. {item['herb_name']:15} ₩{item['total_value']:10,.0f}")

    conn.close()
    return total_value

if __name__ == "__main__":
    total = get_inventory_summary()
    print()
    print("=" * 60)
    print(f"최종 결과: ₩{total:,.0f}")

    if total == 5875708:
        print("⚠️ API와 동일한 값이 나옴!")
    else:
        print(f"✅ 예상값: ₩1,529,434")
        print(f"   차이: ₩{total - 1529434:,.0f}")