import sqlite3
import json

conn = sqlite3.connect('database/kdrug.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()

cursor.execute("""
    SELECT
        pr.receipt_id,
        pr.receipt_date,
        pr.receipt_no,
        pr.total_amount,
        pr.source_file,
        pr.created_at,
        s.name as supplier_name,
        s.supplier_id,
        COUNT(prl.line_id) as line_count,
        SUM(prl.quantity_g) as total_quantity
    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
    LIMIT 1
""")

row = cursor.fetchone()
if row:
    print("Row keys:", row.keys())
    receipt = dict(row)
    for key, value in receipt.items():
        print(f"{key}: {value} (type: {type(value).__name__})")

    # 타입 변환 시도
    if isinstance(receipt.get('receipt_date'), bytes):
        receipt['receipt_date'] = receipt['receipt_date'].decode('utf-8')
    elif receipt.get('receipt_date'):
        receipt['receipt_date'] = str(receipt['receipt_date'])

    if isinstance(receipt.get('created_at'), bytes):
        receipt['created_at'] = receipt['created_at'].decode('utf-8')
    elif receipt.get('created_at'):
        receipt['created_at'] = str(receipt['created_at'])

    print("\nAfter conversion:")
    print(json.dumps(receipt, indent=2))