#!/usr/bin/env python3
"""
详细检查数据库中的 is_latest 标记问题
"""
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("=" * 90)
        print("【詳細檢查：is_latest 標記問題】")
        print("=" * 90)
        
        # 1. 檢查有多少條記錄的 is_latest = true
        cur.execute("SELECT COUNT(*) as cnt FROM journal_entries WHERE is_latest = true AND is_deleted = false")
        true_count = cur.fetchone()[0]
        
        cur.execute("SELECT COUNT(*) as cnt FROM journal_entries WHERE is_latest = false AND is_deleted = false")
        false_count = cur.fetchone()[0]
        
        print(f"\nis_latest 統計:")
        print(f"  is_latest = true:  {true_count} 條")
        print(f"  is_latest = false: {false_count} 條")
        
        # 2. 查看最近創建的仕訳
        print(f"\n【最近100條仕訳】(查看 is_latest 標記)")
        print("-" * 90)
        
        cur.execute("""
            SELECT 
                journal_entry_id,
                entry_date,
                description,
                is_latest,
                revision_count,
                original_entry_id,
                created_at
            FROM journal_entries
            WHERE is_deleted = false
            ORDER BY created_at DESC
            LIMIT 100
        """)
        
        rows = cur.fetchall()
        
        # 分組统计
        is_latest_true = []
        is_latest_false = []
        
        for row in rows:
            je_id, entry_date, desc, is_latest, rev_cnt, orig_id, created_at = row
            if is_latest:
                is_latest_true.append(row)
            else:
                is_latest_false.append(row)
        
        print(f"最近100條中：")
        print(f"  is_latest = true:  {len(is_latest_true)} 條")
        print(f"  is_latest = false: {len(is_latest_false)} 條")
        
        # 3. 查看 test 元記錄
        print(f"\n【test 元 記錄詳細檢查】")
        print("-" * 90)
        
        cur.execute("""
            SELECT 
                journal_entry_id,
                entry_date,
                description,
                is_latest,
                revision_count,
                original_entry_id
            FROM journal_entries
            WHERE description LIKE '%test%'
            AND is_deleted = false
            ORDER BY journal_entry_id DESC
            LIMIT 10
        """)
        
        test_rows = cur.fetchall()
        for row in test_rows:
            je_id, entry_date, desc, is_latest, rev_cnt, orig_id = row
            status = "✓" if is_latest else "✗"
            orig_str = f"→{orig_id}" if orig_id else ""
            print(f"{status} ID={je_id:4d} rev={rev_cnt} {orig_str:>8s} {desc}")
        
        # 4. 檢查同一個 original_entry_id 下是否有多個 is_latest=true
        print(f"\n【檢查同一鏈中的重複 is_latest=true】")
        print("-" * 90)
        
        cur.execute("""
            SELECT 
                original_entry_id,
                COUNT(*) as latest_count,
                STRING_AGG(CAST(journal_entry_id AS text), ',') as ids
            FROM journal_entries
            WHERE is_latest = true 
            AND is_deleted = false
            AND original_entry_id IS NOT NULL
            GROUP BY original_entry_id
            HAVING COUNT(*) > 1
        """)
        
        duplicates = cur.fetchall()
        if duplicates:
            print("發現重複的 is_latest=true！")
            for dup in duplicates:
                orig_id, count, ids = dup
                print(f"  original_entry_id={orig_id}: {count} 條 (IDs: {ids})")
        else:
            print("✓ 沒有發現重複的 is_latest=true")
        
        # 5. 直接執行試算表查詢邏輯，看查詢結果
        print(f"\n【執行試算表查詢（with is_latest=true）】")
        print("-" * 90)
        
        cur.execute("""
            SELECT
                a.account_id,
                a.account_code,
                a.account_name,
                COALESCE(SUM(l.debit), 0)  AS debit,
                COALESCE(SUM(l.credit), 0) AS credit,
                COUNT(DISTINCT e.journal_entry_id) as entry_count
            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 EXTRACT(YEAR FROM e.entry_date) = 2025
            AND EXTRACT(MONTH FROM e.entry_date) = 6
            GROUP BY
                a.account_id,
                a.account_code,
                a.account_name
            ORDER BY
                a.account_code
        """)
        
        tb_rows = cur.fetchall()
        
        total_debit = 0
        total_credit = 0
        
        for row in tb_rows:
            account_id, account_code, account_name, debit, credit, entry_count = row
            total_debit += debit
            total_credit += credit
            
            if '売上高' in account_name or debit > 0 or credit > 0:
                print(f"{account_code:>8s} {account_name:20s} 借:{debit:>15,.2f} 貸:{credit:>15,.2f} (entries: {entry_count})")
        
        print("-" * 90)
        print(f"試算表合計：")
        print(f"  借方: {total_debit:>15,.2f}")
        print(f"  貸方: {total_credit:>15,.2f}")
        print(f"  平衡: {total_debit == total_credit}")
        
        conn.close()

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