#!/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【 当前的试算表结果 (2025年6月) 】\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 '2025-06-01' AND '2025-06-30'
              AND j.is_deleted = false
              AND child.journal_entry_id IS NULL
        """, (aid,))
        row = cur.fetchone()
        print(f"借方 (debit):  {row['debit']}")
        print(f"贳方 (credit): {row['credit']}")
        
        print('\n【 被包含的交易 (child.journal_entry_id IS NULL) 】\n')
        cur.execute("""
            SELECT 
              j.journal_entry_id,
              j.entry_date,
              j.description,
              l.debit,
              l.credit,
              j.parent_entry_id
            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 '2025-06-01' AND '2025-06-30'
              AND j.is_deleted = false
              AND child.journal_entry_id IS NULL
            ORDER BY j.journal_entry_id
        """, (aid,))
        
        total_debit = 0
        total_credit = 0
        print("Entry# | Date       | Debit      | Credit     | Parent | Description")
        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'] or 0:>10} | {row['credit'] or 0:>10} | {parent_str:<6} | {row['description'][:40]}")
            total_debit += row['debit'] or 0
            total_credit += row['credit'] or 0
        
        print("-" * 90)
        print(f"小计:        {total_debit:>10} | {total_credit:>10}")
        
        print('\n【 验证对冲 】\n')
        print('关于1,400,000的对冲:')
        
        # 查询涉及1.4M的被包含的交易
        cur.execute("""
            SELECT 
              j.journal_entry_id,
              j.description,
              l.debit,
              l.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 '2025-06-01' AND '2025-06-30'
              AND j.is_deleted = false
              AND child.journal_entry_id IS NULL
              AND (l.debit = 1400000 OR l.credit = 1400000)
            ORDER BY j.journal_entry_id
        """, (aid,))
        
        hedge_entries = cur.fetchall()
        if hedge_entries:
            print(f"找到{len(hedge_entries)}笔1,400,000的交易:")
            for row in hedge_entries:
                debit_str = f"借{row['debit']}" if row['debit'] else f"贳{row['credit']}"
                print(f"  Entry#{row['journal_entry_id']}: {debit_str} | {row['description'][:50]}")
            
            debit_140 = sum(row['debit'] or 0 for row in hedge_entries)
            credit_140 = sum(row['credit'] or 0 for row in hedge_entries)
            print(f"\n  小计: 借{debit_140}, 贳{credit_140}")
            if debit_140 == credit_140 and debit_140 == 1400000:
                print('  ✓ 这1,400,000的借贳完美对冲了！')
            else:
                print('  ⚠️ 没有完美对冲')
        else:
            print('没有找到1,400,000的交易')
