#!/usr/bin/env python3
"""
详细查看 test 元的最新状态
"""
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:
        print("=" * 100)
        print("【test 元 - 最新完整狀態檢查】")
        print("=" * 100)
        
        # 查詢所有 test 元記錄
        cur.execute("""
            SELECT 
                journal_entry_id,
                entry_date,
                description,
                is_latest,
                revision_count,
                original_entry_id,
                created_at
            FROM journal_entries
            WHERE description LIKE '%test%'
            AND is_deleted = false
            ORDER BY created_at DESC
            LIMIT 10
        """)
        
        rows = cur.fetchall()
        
        print(f"\n最新10筆 test 元記錄：\n")
        print(f"{'ID':>5} {'Date':^10s} {'Latest':^6s} {'Rev':>3s} {'Orig_ID':>7s} {'Created_At':^20s} Description")
        print("-" * 100)
        
        for row in rows:
            je_id, entry_date, desc, is_latest, rev_cnt, orig_id, created_at = row
            status = "✓" if is_latest else "✗"
            orig_str = str(orig_id) if orig_id else "-"
            created_str = str(created_at)[:19] if created_at else "-"
            
            print(f"{je_id:>5d} {str(entry_date):^10s} {status:^6s} {rev_cnt:>3d} {orig_str:>7s} {created_str:^20s} {desc[:30]}")
        
        # 查看最新記錄鏈的詳細情況
        print(f"\n【最新記錄鏈的 701 科目明細】")
        print("-" * 100)
        
        # 找出最新創建的記錄
        cur.execute("""
            SELECT journal_entry_id, original_entry_id, description
            FROM journal_entries
            WHERE description LIKE '%test%'
            AND is_deleted = false
            ORDER BY created_at DESC
            LIMIT 1
        """)
        
        latest = cur.fetchone()
        if latest:
            latest_id, orig_id, desc = latest
            chain_head = orig_id if orig_id else latest_id
            
            print(f"\n最新記錄鏈：")
            print(f"  最新記錄 ID: {latest_id} ({desc})")
            print(f"  原始記錄 ID: {chain_head}\n")
            
            # 查看這條鏈中的所有記錄
            cur.execute("""
                SELECT 
                    je.journal_entry_id,
                    je.description,
                    je.is_latest,
                    je.revision_count,
                    SUM(CASE WHEN a.account_id = 701 THEN COALESCE(jl.debit, 0) ELSE 0 END) as debit_701,
                    SUM(CASE WHEN a.account_id = 701 THEN COALESCE(jl.credit, 0) ELSE 0 END) as credit_701
                FROM journal_entries je
                LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
                LEFT JOIN accounts a ON jl.account_id = a.account_id
                WHERE (je.journal_entry_id = %s OR je.original_entry_id = %s)
                AND je.is_deleted = false
                GROUP BY je.journal_entry_id, je.description, je.is_latest, je.revision_count
                ORDER BY je.journal_entry_id
            """, (chain_head, chain_head))
            
            records = cur.fetchall()
            for rec in records:
                je_id, desc, is_latest, rev_cnt, debit, credit = rec
                status = "✓ LATEST" if is_latest else "✗ OLD"
                print(f"{status} ID={je_id} rev={rev_cnt}: {desc:30s} 借={debit:>7.0f} 貸={credit:>7.0f}")
            
            # 計算這條鏈的合計
            total_debit = sum(r[4] for r in records)
            total_credit = sum(r[5] for r in records)
            print(f"{'':20s} 合計: 借={total_debit:>7.0f} 貸={total_credit:>7.0f}")
            
            # 計算只統計 is_latest 的合計
            is_latest_debit = sum(r[4] for r in records if r[2])
            is_latest_credit = sum(r[5] for r in records if r[2])
            print(f"{'（只統計is_latest）':20s} 借={is_latest_debit:>7.0f} 貸={is_latest_credit:>7.0f}")
        
        conn.close()

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