#!/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 的完整修正链条 】')
        cur.execute("""
            SELECT 
              j.journal_entry_id,
              j.parent_entry_id,
              j.entry_date, 
              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 = %s
            WHERE j.journal_entry_id IN (363, 367, 368)
            ORDER BY j.journal_entry_id
        """, (aid,))
        
        for row in cur.fetchall():
            parent_info = f"Parent={row['parent_entry_id']}" if row['parent_entry_id'] else "Parent=None"
            print(f"  Entry#{row['journal_entry_id']:>3} | {parent_info:<13} | Debit={str(row['debit'] or 0):>10} | Credit={str(row['credit'] or 0):>10} | {row['description'][:50]}")
        
        print('\n【 Entry#207 的完整修正链条 】')
        cur.execute("""
            SELECT 
              j.journal_entry_id,
              j.parent_entry_id,
              j.entry_date, 
              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 = %s
            WHERE j.journal_entry_id IN (207, 369)
            ORDER BY j.journal_entry_id
        """, (aid,))
        
        for row in cur.fetchall():
            parent_info = f"Parent={row['parent_entry_id']}" if row['parent_entry_id'] else "Parent=None"
            print(f"  Entry#{row['journal_entry_id']:>3} | {parent_info:<13} | Debit={str(row['debit'] or 0):>10} | Credit={str(row['credit'] or 0):>10} | {row['description'][:50]}")

        print('\n【 问题分析 】')
        print('1) 如果要包含Entry#363: credit=640,000')
        print('   - 但Entry#363被作为Entry#367的父仕訳，应该被排除')
        print('')
        print('2) 预期值4,082,728从何而来？')
        print('   - 当前查询结果: 5,482,728')
        print('   - 差异: 1,400,000')
        print('   - 被排除的1,910,000中包含了Entry#363的640,000和Entry#207的1,270,000')
        print('')
        print('3) 用户是否说了具体的期望金额来自哪里？')

        print('\n【 完整的科目701 2025年6月交易汇总 】')
        cur.execute("""
            SELECT 
              SUM(CASE WHEN parent_entry_id IS NULL AND (SELECT COUNT(*) FROM journal_entries child WHERE child.parent_entry_id = journal_entries.journal_entry_id) = 0 
                 THEN COALESCE(l.credit, 0) ELSE 0 END) as included_credit,
              SUM(CASE WHEN parent_entry_id IS NOT NULL OR (SELECT COUNT(*) FROM journal_entries child WHERE child.parent_entry_id = journal_entries.journal_entry_id) > 0
                 THEN COALESCE(l.credit, 0) ELSE 0 END) as excluded_credit,
              SUM(COALESCE(l.credit, 0)) as total_credit
            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.entry_date >= '2025-06-01'
              AND j.entry_date <= '2025-06-30'
              AND j.is_deleted = false
        """, (aid,))
        row = cur.fetchone()
        print(f"  包含的credit: {row['included_credit']}")
        print(f"  排除的credit: {row['excluded_credit']}")
        print(f"  总计credit: {row['total_credit']}")
