#!/usr/bin/env python3
"""
查詢 701 科目（売上高）的所有詳細記錄
"""
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("【701 科目（売上高）的所有記錄 - 2025年6月】")
        print("=" * 100)
        
        # 查詢所有涉及 701 科目的仕訳
        cur.execute("""
            SELECT 
                e.journal_entry_id,
                e.entry_date,
                e.description,
                e.is_latest,
                e.revision_count,
                e.original_entry_id,
                COALESCE(l.debit, 0) as debit,
                COALESCE(l.credit, 0) as credit
            FROM journal_entries e
            LEFT JOIN journal_lines l ON e.journal_entry_id = l.journal_entry_id
            WHERE e.is_deleted = false
            AND e.entry_date >= '2025-06-01' 
            AND e.entry_date <= '2025-06-30'
            AND (l.account_id = 701 OR e.description LIKE '%test%')
            ORDER BY e.journal_entry_id DESC
        """)
        
        rows = cur.fetchall()
        
        print(f"\n總共 {len(rows)} 條明細記錄\n")
        print(f"{'ID':>4s} {'Date':^10s} {'Latest':^6s} {'Rev':>3s} {'Orig ID':>7s} {'Debit':>12s} {'Credit':>12s} Description")
        print("-" * 100)
        
        total_debit = 0
        total_credit = 0
        is_latest_debit = 0
        is_latest_credit = 0
        
        for row in rows:
            je_id, entry_date, desc, is_latest, rev_cnt, orig_id, debit, credit = row
            status = "✓" if is_latest else " "
            orig_str = str(orig_id) if orig_id else "-"
            
            total_debit += debit
            total_credit += credit
            if is_latest:
                is_latest_debit += debit
                is_latest_credit += credit
            
            desc_short = desc[:35] if desc else "-"
            print(f"{je_id:>4d} {str(entry_date):^10s} {status:^6s} {rev_cnt:>3d} {orig_str:>7s} {debit:>12,.0f} {credit:>12,.0f} {desc_short}")
        
        print("-" * 100)
        print(f"{'統計':^35s} 合計借方: {total_debit:>12,.0f} 合計貸方: {total_credit:>12,.0f}")
        print(f"{'（只統計is_latest=true）':^35s} 借方: {is_latest_debit:>12,.0f} 貸方: {is_latest_credit:>12,.0f}")
        
        # 檢查是否有 is_latest=false 但不在任何修正鏈中的記錄
        print(f"\n【檢查孤立的 is_latest=false 記錄】")
        print("-" * 100)
        
        cur.execute("""
            SELECT 
                journal_entry_id,
                description,
                is_latest,
                revision_count,
                original_entry_id
            FROM journal_entries
            WHERE is_deleted = false
            AND (description LIKE '%test%' OR description LIKE '%売上%')
            AND is_latest = false
            AND original_entry_id IS NULL
        """)
        
        orphans = cur.fetchall()
        if orphans:
            print("發現孤立的 is_latest=false 記錄（沒有 original_entry_id）：")
            for orphan in orphans:
                print(f"  ID={orphan[0]}: {orphan[1]}")
        else:
            print("✓ 沒有孤立的 is_latest=false 記錄")
        
        conn.close()

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