#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
입고장 상세보기 오류 디버그
"""

import sqlite3
import traceback

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

    receipt_id = 6

    print("=== 1. 입고장 헤더 조회 ===")
    try:
        cursor.execute("""
            SELECT
                pr.*,
                s.name as supplier_name,
                s.business_no as supplier_business_no,
                s.phone as supplier_phone
            FROM purchase_receipts pr
            JOIN suppliers s ON pr.supplier_id = s.supplier_id
            WHERE pr.receipt_id = ?
        """, (receipt_id,))

        receipt = cursor.fetchone()
        if receipt:
            receipt_dict = dict(receipt)
            print("헤더 조회 성공!")
            for key, value in receipt_dict.items():
                print(f"  {key}: {value} (type: {type(value).__name__})")
        else:
            print("입고장을 찾을 수 없습니다.")
            return
    except Exception as e:
        print(f"헤더 조회 오류: {e}")
        traceback.print_exc()
        return

    print("\n=== 2. 입고장 상세 라인 조회 ===")
    try:
        cursor.execute("""
            SELECT
                prl.*,
                h.herb_name,
                h.insurance_code,
                il.lot_id,
                il.quantity_onhand as current_stock
            FROM purchase_receipt_lines prl
            JOIN herb_items h ON prl.herb_item_id = h.herb_item_id
            LEFT JOIN inventory_lots il ON prl.line_id = il.receipt_line_id
            WHERE prl.receipt_id = ?
            ORDER BY prl.line_id
        """, (receipt_id,))

        lines = cursor.fetchall()
        print(f"라인 수: {len(lines)}개")

        if lines:
            first_line = dict(lines[0])
            print("\n첫 번째 라인 데이터:")
            for key, value in first_line.items():
                print(f"  {key}: {value} (type: {type(value).__name__})")
    except Exception as e:
        print(f"라인 조회 오류: {e}")
        traceback.print_exc()

    print("\n=== 3. JSON 변환 테스트 ===")
    try:
        import json

        # receipt_data 구성
        receipt_data = dict(receipt)
        receipt_data['lines'] = [dict(row) for row in lines]

        # JSON 변환 시도
        json_str = json.dumps(receipt_data, ensure_ascii=False, default=str)
        print("JSON 변환 성공!")
        print(f"JSON 길이: {len(json_str)} 문자")

    except Exception as e:
        print(f"JSON 변환 오류: {e}")
        traceback.print_exc()

        # 문제가 되는 필드 찾기
        print("\n각 필드별 JSON 변환 테스트:")
        for key, value in receipt_data.items():
            try:
                json.dumps({key: value}, default=str)
                print(f"  ✓ {key}: OK")
            except Exception as field_error:
                print(f"  ✗ {key}: {field_error}")
                print(f"    값: {value}")
                print(f"    타입: {type(value)}")

    conn.close()

if __name__ == "__main__":
    debug_receipt_detail()