import sys
sys.path.insert(0, '/app')

from app.core.database import get_connection

print("=" * 80)
print("【Chain 140 の各バージョンの科目内訳】")
print("=" * 80)

chain_id = 140
entry_ids = [140, 438, 461]

with get_connection() as conn:
    with conn.cursor() as cur:
        for entry_id in entry_ids:
            cur.execute("""
                SELECT je.journal_entry_id, je.revision_count, je.is_latest, je.entry_date
                FROM journal_entries je
                WHERE je.journal_entry_id = %s
            """, [entry_id])
            
            entry = cur.fetchone()
            print(f"\n【ID {entry_id} (v{entry['revision_count']}, latest={entry['is_latest']})】")
            print(f"日付: {entry['entry_date']}")
            
            cur.execute("""
                SELECT 
                    a.account_id,
                    a.account_code,
                    a.account_name,
                    COALESCE(jl.debit, 0) as debit,
                    COALESCE(jl.credit, 0) as credit
                FROM journal_lines jl
                JOIN accounts a ON jl.account_id = a.account_id
                WHERE jl.journal_entry_id = %s
                ORDER BY a.account_id
            """, [entry_id])
            
            lines = cur.fetchall()
            print(f"  行数: {len(lines)}")
            for line in lines:
                debit_display = f"借方 {line['debit']}" if line['debit'] > 0 else ""
                credit_display = f"貸方 {line['credit']}" if line['credit'] > 0 else ""
                side = (debit_display + " " + credit_display).strip()
                marker = " ← 古いバージョンにない科目" if line['account_id'] == 19 and entry_id == 461 else ""
                print(f"    • {line['account_id']} ({line['account_code']}) {line['account_name']}: {side}{marker}")

print("\n" + "=" * 80)
print("【結論】")
print("修正前バージョンと修正後バージョンで科目構成が異なります。")
print("古いバージョンには account_id 19（買掛金）がないため、")
print("account_id 19 でフィルターした場合、最新バージョンのみが返されます。")
print("=" * 80)
