#!/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
from decimal import Decimal

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【 2025年6月701（売上高）的借方交易 】\n')
        cur.execute("""
            SELECT 
              jl.journal_line_id,
              jl.journal_entry_id,
              je.entry_date,
              je.description,
              jl.debit,
              jl.credit,
              je.parent_entry_id,
              je.is_deleted,
              (SELECT COUNT(*) FROM journal_entries child WHERE child.parent_entry_id = je.journal_entry_id) as has_child
            FROM journal_lines jl
            JOIN journal_entries je ON je.journal_entry_id = jl.journal_entry_id
            WHERE jl.account_id = %s
              AND je.entry_date >= '2025-06-01'
              AND je.entry_date <= '2025-06-30'
              AND jl.debit > 0
            ORDER BY je.entry_date, je.journal_entry_id
        """, (aid,))
        
        total_debit = 0
        print("Entry# | Date       | Debit      | Parent | HasChild | Description (first 50 chars)")
        print("-" * 90)
        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} | {row['entry_date']} | {row['debit']:>10} | {parent_str:<6} | {row['has_child']:<8} | {row['description'][:50]}")
            total_debit += row['debit']
        
        print("-" * 90)
        print(f"总计借方: {total_debit}")
        
        print('\n【 按照LEFT JOIN过滤逻辑 】\n')
        print('当前SQL: child.journal_entry_id IS NULL')
        print('= 只包含没有子交易的交易')
        print('')
        print('关键问题:')
        print('- Entry#360 (debit=1,400,000) 现在 parent_entry_id=357')
        print('- 但Entry#360本身还是被包含的（因为它没有子交易），只是Entry#357被过滤了')
        print('')
        
        print('\n【 验证当前的SQL过滤结果 】\n')
        cur.execute("""
            SELECT
                COALESCE(SUM(l.debit), 0)  AS debit,
                COALESCE(SUM(l.credit), 0) AS credit
            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 %s AND %s
              AND j.is_deleted = false
              AND child.journal_entry_id IS NULL
        """, (aid, '2025-06-01', '2025-06-30'))
        row = cur.fetchone()
        print(f"当前SQL查询结果:")
        print(f"  借方 (debit) = {row['debit']}")
        print(f"  貸方 (credit) = {row['credit']}")
        
        print('\n【 分析 】')
        print('Entry#360的1,400,000借方是"取消"交易')
        print('它与Entry#357形成对冲:')
        print('  Entry#357: 贷方1,400,000 (原始业务)')
        print('  Entry#360: 借方1,400,000 (取消)')
        print('')
        print('问题: 这两个是相互抵消的关系，不应该同时出现自一个科目的报告里')
        print('      current logic 过滤掉了Entry#357，但Entry#360仍然被计入')
        print('')
        print('可能的解决方案:')
        print('1. 当parent_entry_id不为NULL时，该交易也应被排除')
        print('2. 或者: Entry#360应该成为"leaf"，后续有更正交易')
