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

import os
import sys
sys.path.insert(0, 'backend')

os.environ['DB_HOST'] = '192.168.0.61'
os.environ['DB_NAME'] = 'njts_acct'
os.environ['DB_USER'] = 'njts_app'
os.environ['DB_PASSWORD'] = 'njts_app2025'
os.environ['DB_PORT'] = '55432'

from app.core.database import get_connection

with get_connection() as conn:
    with conn.cursor() as cur:
        # 获取account_id
        cur.execute("SELECT account_id FROM accounts WHERE account_code = '701'")
        aid = cur.fetchone()['account_id']
        
        print('\n【 關於1,400,000的借方是否應該對冲 】\n')
        
        print('被包含的借方交易：\n')
        cur.execute("""
            SELECT 
              j.journal_entry_id,
              j.entry_date,
              j.description,
              l.debit,
              j.parent_entry_id,
              (SELECT COUNT(*) FROM journal_entries child WHERE child.parent_entry_id = j.journal_entry_id) as has_child
            FROM journal_lines l
            JOIN journal_entries j
                ON j.journal_entry_id = l.journal_entry_id
            LEFT JOIN journal_entries child
                ON child.parent_entry_id = j.journal_entry_id
            WHERE l.account_id = %s
              AND j.entry_date BETWEEN '2025-06-01' AND '2025-06-30'
              AND j.is_deleted = false
              AND child.journal_entry_id IS NULL
              AND l.debit > 0
            ORDER BY j.journal_entry_id
        """, (aid,))
        
        debit_entries = cur.fetchall()
        for row in debit_entries:
            parent_str = f"Parent=#{row['parent_entry_id']}" if row['parent_entry_id'] else "Parent=None"
            print(f"Entry#{row['journal_entry_id']}: {row['debit']:>10} {parent_str:<12} {row['description'][:45]}")
        
        print('\n【 分析 】\n')
        
        # 查找對應的貳方（原始交易）
        print('对于Entry#373 (借1,400,000)：')
        print('  - Parent: Entry#372')
        print('  - Entry#372 Parent: Entry#360')  
        print('  - Entry#360 Parent: Entry#357')
        print('  - Entry#357: 貳1,400,000 ← 這是對應的原始交易\n')
        
        print('修正链条流程：')
        print('  1) Entry#357 (貳1.4M) - 原始業務被取消')
        print('  2) Entry#360 (借1.4M) - 取消交易')
        print('  3) Entry#372 (貳1.4M) - 逆仕訳（對沖borrowed #360）')
        print('  4) Entry#373 (借1.4M) - 修正款（收分回平衡）\n')
        
        print('根據修正邏輯：')
        print('  - Entry#357 被過濾（有子）')
        print('  - Entry#360 被過濾（有子）')
        print('  - Entry#372 被過濾（有子）')
        print('  - Entry#373 被保留（無子）← 最終結果：借1.4M\n')
        
        print('問題：')
        print('  這1.4M的借方是修正鏈最後的「平衡」交易')
        print('  它本身對應的是原始貸方的對沖')
        print('  按修正邏輯，似乎正確\n')
        
        print('可能的情況：')
        print('  1) 如果「對冲」意味著完全抵消，Entry#373可能不應該被計入')
        print('  2) 或者這是正確的，因為最後有修正交易調整')
        print('  3) 需要確認業務邏輯')
