#!/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#357 和 Entry#360 的关系 】')
        cur.execute("""
            SELECT 
              j.journal_entry_id,
              j.parent_entry_id,
              j.entry_date, 
              j.description,
              l.debit,
              l.credit,
              j.is_deleted
            FROM journal_entries j
            LEFT JOIN journal_lines l ON l.journal_entry_id = j.journal_entry_id AND l.account_id = %s
            WHERE j.journal_entry_id IN (357, 360)
            ORDER BY j.journal_entry_id
        """, (aid,))
        
        print("Entry# | Parent | Debit      | Credit     | Description (first 60 chars)")
        for row in cur.fetchall():
            parent_info = f"{row['parent_entry_id']}" if row['parent_entry_id'] else "None"
            desc = row['description'] if row['description'] else ""
            print(f"#{row['journal_entry_id']:<5} | {parent_info:<6} | {str(row['debit'] or 0):>10} | {str(row['credit'] or 0):>10} | {desc[:60]}")
        
        print('\n【 发现问题了！】')
        print('Entry#357: credit=1,400,000 (【未計上のため...】描述的原始交易)')
        print('Entry#360: debit=1,400,000 (【未計上のため取消】取消交易)')
        print('')
        print('这个1,400,000的交易不应该被计入：')
        print('  当前结果 5,482,728 应该 - 1,400,000 = 4,082,728 ✓')
        print('')
        print('问题是：Entry#360没有设置parent_entry_id指向Entry#357')
        print('所以LEFT JOIN过滤逻辑无法识别这个取消关系。')
        print('')
        print('解决方案之一：检查Entry#360是否应该有 parent_entry_id=357')
