#!/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:
        print('\n【 Entry#371 的信息 】\n')
        cur.execute("""
            SELECT 
              j.journal_entry_id,
              j.entry_date,
              j.description,
              j.parent_entry_id,
              j.is_deleted
            FROM journal_entries j
            WHERE j.journal_entry_id = 371
        """)
        row = cur.fetchone()
        if row:
            print(f"Entry#371 详细信息:")
            print(f"  日期: {row['entry_date']}")
            print(f"  描述: {row['description']}")
            print(f"  Parent: {row['parent_entry_id'] or 'None'}")
            print(f"  已删除: {row['is_deleted']}")
        
        print('\n【 Entry#357-373 的完整链条 】\n')
        cur.execute("""
            SELECT 
              j.journal_entry_id,
              j.parent_entry_id,
              j.description,
              l.debit,
              l.credit
            FROM journal_entries j
            LEFT JOIN journal_lines l ON l.journal_entry_id = j.journal_entry_id AND l.account_id = (
              SELECT account_id FROM accounts WHERE account_code = '701'
            )
            WHERE j.journal_entry_id IN (357, 360, 371, 372, 373)
            ORDER BY j.journal_entry_id
        """)
        
        print("链条分析:")
        print("Entry# | Parent# | 借方       | 贳方       | 说明")
        print("-" * 70)
        for row in cur.fetchall():
            parent_str = f"#{row['parent_entry_id']}" if row['parent_entry_id'] else "None"
            debit = row['debit'] or 0
            credit = row['credit'] or 0
            
            if row['journal_entry_id'] == 357:
                note = "原始业务（被链接作为父）"
            elif row['journal_entry_id'] == 360:
                note = "取消交易（第二步，parent=357）"
            elif row['journal_entry_id'] == 371:
                note = "独立的贳方交易（未链接！）⚠️"
            elif row['journal_entry_id'] == 372:
                note = "逆仕訳（第三步，parent=360）"
            elif row['journal_entry_id'] == 373:
                note = "修正交易（第四步，parent=372）"
            else:
                note = ""
            
            print(f"#{row['journal_entry_id']:<6} | {parent_str:<7} | {debit:>10} | {credit:>10} | {note}")
        
        print('\n【 问题分析 】\n')
        print('按照LEFT JOIN过滤逻辑（child.journal_entry_id IS NULL）:')
        print('')
        print('Entry#357: 被过滤（有子#360）')
        print('Entry#360: 被过滤（有子#372）')
        print('Entry#371: 被包含！（无子）← 独立的贳1,400,000')
        print('Entry#372: 被过滤（有子#373）')
        print('Entry#373: 被包含！（无子）← 独立的借1,400,000')
        print('')
        print('结果:')
        print('  对于这组交易: 借1.4M (Entry#373) + 贳1.4M (Entry#371) = 相互抵消了')
        print('')
        print('问题:')
        print('  Entry#371 和 Entry#373 有重复的金额，但它们不属于同一个修正链')
        print('  Entry#371应该被删除，或者Entry#371应该是Entry#360的直接取消（parent=360）')
