#!/usr/bin/env python3
"""
直接查询数据库验证试算表数据
"""
import psycopg

try:
    conn = psycopg.connect(
        host='192.168.0.61',
        port=55432,
        dbname='njts_acct',
        user='njts_app',
        password='njts_app2025'
    )
    
    with conn.cursor() as cur:
        # 执行试算表查询逻辑（与后端相同）
        sql = """
            SELECT
                a.account_id,
                a.account_code,
                a.account_name,
                a.account_type,
                COALESCE(SUM(l.debit), 0)  AS debit,
                COALESCE(SUM(l.credit), 0) AS credit
            FROM journal_lines l
            JOIN journal_entries e ON e.journal_entry_id = l.journal_entry_id
            JOIN accounts a ON a.account_id = l.account_id
            WHERE e.is_deleted = false
            AND e.is_latest = true
            AND e.entry_date >= '2025-06-01'
            AND e.entry_date <= '2025-06-30'
            AND e.fiscal_year = 2025
            GROUP BY
                a.account_id,
                a.account_code,
                a.account_name,
                a.account_type
            ORDER BY
                a.account_code
        """
        
        cur.execute(sql)
        rows = cur.fetchall()
        
        print("=" * 80)
        print("【試算表查詢結果 - 2025年6月 - 只統計 is_latest=TRUE 的記錄】")
        print("=" * 80)
        print(f"\n總共 {len(rows)} 個科目\n")
        
        # 打印關鍵科目
        relevant_codes = []
        for row in rows:
            account_code, account_name, debit, credit = row[1], row[2], row[4], row[5]
            relevant_codes.append((account_code, account_name, debit, credit))
        
        # 查找 sales 相关科目
        for code, name, debit, credit in relevant_codes:
            if '売上高' in name or 'test' in name.lower():
                print(f"科目コード: {code}")
                print(f"科目名: {name}")
                print(f"  借方: {debit:>18,.2f}")
                print(f"  貸方: {credit:>18,.2f}")
                print()
        
        # 計算總借貸
        total_debit = sum(row[4] for row in rows)
        total_credit = sum(row[5] for row in rows)
        
        print("-" * 80)
        print(f"試算表合計：")
        print(f"  総借方: {total_debit:>18,.2f}")
        print(f"  総貸方: {total_credit:>18,.2f}")
        print(f"  差額: {total_debit - total_credit:>18,.2f}")
        
        if abs(total_debit - total_credit) < 0.01:
            print("\n✓ 借貸平衡！")
        else:
            print("\n✗ 借貸不平衡！")
        
        # 查詢 test元 的詳細情況
        print("\n" + "=" * 80)
        print("【test 元 詳細查詢】")
        print("=" * 80)
        
        cur.execute("""
            SELECT 
                e.journal_entry_id,
                e.entry_date,
                e.description,
                e.is_latest,
                e.revision_count,
                e.original_entry_id,
                SUM(CASE WHEN a.account_name LIKE '%売上高%' THEN l.credit ELSE 0 END) as sales_credit
            FROM journal_entries e
            LEFT JOIN journal_lines l ON e.journal_entry_id = l.journal_entry_id
            LEFT JOIN accounts a ON l.account_id = a.account_id
            WHERE e.is_deleted = false
            AND e.description LIKE '%test%'
            GROUP BY e.journal_entry_id, e.entry_date, e.description, e.is_latest, e.revision_count, e.original_entry_id
            ORDER BY e.journal_entry_id DESC
            LIMIT 5
        """)
        
        test_rows = cur.fetchall()
        print("\n最新の 5 筆 test 元 記錄：\n")
        for row in test_rows:
            je_id, entry_date, desc, is_latest, rev_cnt, orig_id, sales_credit = row
            status = "✓ LATEST" if is_latest else "  old"
            sales_str = f"{sales_credit:,.2f}" if sales_credit else "0"
            print(f"{status} ID={je_id} rev={rev_cnt} orig={orig_id} {desc[:35]}")
            print(f"        売上高貸方: {sales_str}")
        
        conn.close()

except Exception as e:
    print(f'錯誤: {e}')
    import traceback
    traceback.print_exc()
