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

import sqlite3

# 데이터베이스 연결
conn = sqlite3.connect('database/kdrug.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()

print("=== 입고장별 총금액 확인 ===\n")

# 각 입고장의 라인별 총액 확인
cursor.execute("""
    SELECT
        pr.receipt_id,
        pr.receipt_date,
        s.name as supplier_name,
        COUNT(prl.line_id) as line_count,
        SUM(prl.quantity_g) as total_quantity,
        SUM(prl.line_total) as calculated_total
    FROM purchase_receipts pr
    JOIN suppliers s ON pr.supplier_id = s.supplier_id
    LEFT JOIN purchase_receipt_lines prl ON pr.receipt_id = prl.receipt_id
    GROUP BY pr.receipt_id
    ORDER BY pr.receipt_date DESC
""")

results = cursor.fetchall()

for row in results:
    print(f"입고장 ID: {row['receipt_id']}")
    print(f"  날짜: {row['receipt_date']}")
    print(f"  도매상: {row['supplier_name']}")
    print(f"  품목 수: {row['line_count']}개")
    print(f"  총 수량: {row['total_quantity']}g")
    print(f"  총 금액: {row['calculated_total']:,.0f}원" if row['calculated_total'] else "  총 금액: 0원")
    print("-" * 40)

print("\n=== 입고장 라인 상세 (첫 번째 입고장) ===\n")

# 첫 번째 입고장의 라인 상세 확인
if results:
    first_receipt_id = results[0]['receipt_id']
    cursor.execute("""
        SELECT
            herb_item_id,
            quantity_g,
            unit_price_per_g,
            line_total
        FROM purchase_receipt_lines
        WHERE receipt_id = ?
        LIMIT 5
    """, (first_receipt_id,))

    lines = cursor.fetchall()
    for line in lines:
        print(f"약재 ID: {line['herb_item_id']}")
        print(f"  수량: {line['quantity_g']}g")
        print(f"  단가: {line['unit_price_per_g']}원/g")
        print(f"  라인 총액: {line['line_total']}원")
        print(f"  계산 검증: {line['quantity_g']} × {line['unit_price_per_g']} = {line['quantity_g'] * line['unit_price_per_g']}원")
        print()

conn.close()