#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Verify the correction logic is working correctly
Check test entries (ID=431, 432) 
"""
import sys
sys.path.insert(0, '/app')

from app.core.database import get_connection

def verify():
    with get_connection() as conn:
        with conn.cursor() as cur:
            print("=" * 80)
            print("【修正ロジックの検証: test 元（ID=431、432）】")
            print("=" * 80)
            print()
            
            print("【step 1: 修正チェーンの構造確認】")
            cur.execute("""
                SELECT 
                    journal_entry_id,
                    description,
                    is_latest,
                    is_deleted,
                    parent_entry_id,
                    original_entry_id,
                    entry_date,
                    created_at,
                    revision_count
                FROM journal_entries
                WHERE journal_entry_id IN (431, 432)
                ORDER BY journal_entry_id
            """)
            
            entries = cur.fetchall()
            for e in entries:
                print(f"\nID={e['journal_entry_id']}:")
                print(f"  説明: {e['description']}")
                print(f"  is_latest: {e['is_latest']} {'✓最新版' if e['is_latest'] else '✗旧版'}")
                print(f"  is_deleted: {e['is_deleted']}")
                print(f"  parent_entry_id: {e['parent_entry_id']}")
                print(f"  original_entry_id: {e['original_entry_id']}")
                print(f"  entry_date: {e['entry_date']}")
                print(f"  created_at: {e['created_at']}")
                print(f"  revision_count: {e['revision_count']}")
            
            print()
            print("【Step 2: 各エントリの仕訳行詳細】")
            
            for eid in [431, 432]:
                print(f"\nID={eid}:")
                cur.execute("""
                    SELECT 
                        a.account_code,
                        a.account_name,
                        l.debit,
                        l.credit
                    FROM journal_lines l
                    JOIN accounts a ON a.account_id = l.account_id
                    WHERE l.journal_entry_id = %s
                    ORDER BY a.account_code
                """, (eid,))
                
                lines = cur.fetchall()
                for line in lines:
                    print(f"  {line['account_code']} {line['account_name']:<15s} | 借={line['debit']:>10.0f} 貸={line['credit']:>10.0f}")
            
            print()
            print("【Step 3: is_latest=true フィルターでのみ統計】")
            cur.execute("""
                SELECT 
                    SUM(CASE WHEN l.account_id = (SELECT account_id FROM accounts WHERE account_code = '5') THEN l.debit ELSE 0 END) as debit_5,
                    SUM(CASE WHEN l.account_id = (SELECT account_id FROM accounts WHERE account_code = '5') THEN l.credit ELSE 0 END) as credit_5,
                    SUM(CASE WHEN l.account_id = (SELECT account_id FROM accounts WHERE account_code = '41') THEN l.debit ELSE 0 END) as debit_41,
                    SUM(CASE WHEN l.account_id = (SELECT account_id FROM accounts WHERE account_code = '41') THEN l.credit ELSE 0 END) as credit_41
                FROM journal_lines l
                JOIN journal_entries j ON j.journal_entry_id = l.journal_entry_id
                WHERE (l.journal_entry_id = 431 OR l.journal_entry_id = 432)
                AND j.is_latest = true
            """)
            
            result = cur.fetchone()
            print(f"売掛金（5）: 借={result['debit_5']:>10.0f} 貸={result['credit_5']:>10.0f}")
            print(f"売上高（41）: 借={result['debit_41']:>10.0f} 貸={result['credit_41']:>10.0f}")
            
            print()
            print("✓ 検証完了")

if __name__ == "__main__":
    try:
        verify()
    except Exception as e:
        print(f"エラー: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
