import psycopg
from datetime import datetime

# 連接到数据库
conn = psycopg.connect(
    host="127.0.0.1",
    port=5432,
    dbname="njts_accounting",
    user="postgres",
    password="postgres"
)

try:
    with conn:
        with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
            print("=" * 80)
            print("【デバッグ: ID=431と432のis_latest値の確認】")
            print("=" * 80)
            
            # Check if is_latest column exists
            cur.execute("""
                SELECT COUNT(*) as cnt
                FROM information_schema.columns 
                WHERE table_name = 'journal_entries' AND column_name = 'is_latest'
            """)
            col_exists = cur.fetchone()['cnt'] > 0
            print(f"is_latest列が存在: {col_exists}")
            print()
            
            # Check the test entries
            cur.execute("""
                SELECT 
                    journal_entry_id,
                    description,
                    is_latest,
                    is_deleted,
                    parent_entry_id,
                    original_entry_id
                FROM journal_entries
                WHERE journal_entry_id IN (431, 432)
                ORDER BY journal_entry_id
            """)
            entries = cur.fetchall()
            for e in entries:
                print(f"ID={e['journal_entry_id']}: {e['description']}")
                print(f"  is_latest={e['is_latest']}, is_deleted={e['is_deleted']}")
                print(f"  parent_entry_id={e['parent_entry_id']}, original_entry_id={e['original_entry_id']}")
                print()
            
            print("=" * 80)
            print("【デバッグ: 修正後のサービスロジックで701科目をクエリ】")
            print("=" * 80)
            
            # Get account id for 701
            cur.execute("SELECT account_id FROM accounts WHERE account_code = '701'")
            acc_result = cur.fetchone()
            if acc_result:
                account_id = acc_result['account_id']
                
                # Execute the same query as the service with is_latest = true
                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
                    WHERE l.account_id = %s
                        AND j.entry_date BETWEEN '2025-01-01' AND '2025-12-31'
                        AND j.is_deleted = false
                        AND j.is_latest = true
                """, (account_id,))
                
                result = cur.fetchone()
                print(f"701科目の試算表（is_latest=true）:")
                print(f"  借方: {result['debit']}")
                print(f"  貸方: {result['credit']}")
                print()
            
            print("=" * 80)
            print("【デバッグ: 701科目のすべての仕訳行を確認】")
            print("=" * 80)
            
            cur.execute("""
                SELECT 
                    j.journal_entry_id,
                    j.description,
                    j.is_latest,
                    j.is_deleted,
                    l.debit,
                    l.credit
                FROM journal_lines l
                JOIN journal_entries j ON j.journal_entry_id = l.journal_entry_id
                JOIN accounts a ON a.account_id = l.account_id
                WHERE a.account_code = '701'
                AND j.is_deleted = false
                ORDER BY j.journal_entry_id
            """)
            
            lines = cur.fetchall()
            print(f"合計: {len(lines)}行")
            print()
            
            total_debit = 0
            total_credit = 0
            for line in lines:
                status = "✓" if line['is_latest'] else "✗"
                print(f"{status} ID={line['journal_entry_id']:4d}: {line['description']:30s} | 借={line['debit']:10.0f} 貸={line['credit']:10.0f} | is_latest={line['is_latest']}")
                total_debit += line['debit']
                total_credit += line['credit']
            
            print()
            print(f"【全行合計】借={total_debit:.0f}, 貸={total_credit:.0f}")
            print()
            
            # Count by is_latest
            cur.execute("""
                SELECT 
                    j.is_latest,
                    COUNT(*) as count,
                    COALESCE(SUM(l.debit), 0) as total_debit,
                    COALESCE(SUM(l.credit), 0) as total_credit
                FROM journal_lines l
                JOIN journal_entries j ON j.journal_entry_id = l.journal_entry_id
                JOIN accounts a ON a.account_id = l.account_id
                WHERE a.account_code = '701'
                AND j.is_deleted = false
                GROUP BY j.is_latest
                ORDER BY j.is_latest DESC
            """)
            
            stats = cur.fetchall()
            print("【is_latestごとの集計】")
            for stat in stats:
                status = "最新" if stat['is_latest'] else "旧版"
                print(f"{status}: {stat['count']}行 | 借={stat['total_debit']:.0f} 貸={stat['total_credit']:.0f}")

finally:
    conn.close()
