#!/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【 Entry#363 和 Entry#367 形成的模式（成功的修正链) 】\n')
        cur.execute("""
            SELECT 
              j.journal_entry_id,
              j.parent_entry_id,
              j.entry_date,
              j.description,
              (SELECT SUM(l.credit) FROM journal_lines l WHERE l.journal_entry_id = j.journal_entry_id AND l.account_id = %s) as credit,
              (SELECT SUM(l.debit) FROM journal_lines l WHERE l.journal_entry_id = j.journal_entry_id AND l.account_id = %s) as debit
            FROM journal_entries j
            WHERE j.journal_entry_id IN (363, 367, 368)
            ORDER BY j.journal_entry_id
        """, (aid, aid))
        
        print("Entry# | Parent | Credit     | Debit      | Description (first 50 chars)")
        for row in cur.fetchall():
            parent_str = f"#{row['parent_entry_id']}" if row['parent_entry_id'] else "None"
            print(f"#{row['journal_entry_id']:<5} | {parent_str:<6} | {str(row['credit'] or 0):>10} | {str(row['debit'] or 0):>10} | {row['description'][:50]}")
        
        print('\n这是一个3步修正链:')
        print('  363 (原始贷:640,000) → 367 (逆仕訳借:640,000) → 368 (修正后贷:640,000)')
        print('')
        print('\n【 Entry#357 和 Entry#360 的模式（不完整的取消链) 】\n')
        cur.execute("""
            SELECT 
              j.journal_entry_id,
              j.parent_entry_id,
              j.entry_date,
              j.description,
              (SELECT SUM(l.credit) FROM journal_lines l WHERE l.journal_entry_id = j.journal_entry_id AND l.account_id = %s) as credit,
              (SELECT SUM(l.debit) FROM journal_lines l WHERE l.journal_entry_id = j.journal_entry_id AND l.account_id = %s) as debit
            FROM journal_entries j
            WHERE j.journal_entry_id IN (357, 360)
            ORDER BY j.journal_entry_id
        """, (aid, aid))
        
        print("Entry# | Parent | Credit     | Debit      | Description (first 50 chars)")
        for row in cur.fetchall():
            parent_str = f"#{row['parent_entry_id']}" if row['parent_entry_id'] else "None"
            print(f"#{row['journal_entry_id']:<5} | {parent_str:<6} | {str(row['credit'] or 0):>10} | {str(row['debit'] or 0):>10} | {row['description'][:50]}")
        
        print('\n这是一个2步取消链:')
        print('  357 (原始贷:1,400,000) → 360 (取消借:1,400,000)')
        print('')
        print('⚠️ 问题：Entry#360没有后续的修正交易！')
        print('')
        print('应该有第三步来平衡：')
        print('  360 (取消借:1,400,000) → ??? (修正后贷:1,400,000) ← 缺失！')
        print('')
        print('解决方案:')
        print('  需要检查是否应该创建一个后续的修正交易')
        print('  或者改变过滤逻辑使Entry#360也被排除')
