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

from app.core.database import get_connection

print("=" * 80)
print("【Chain ID 140 の詳細分析】")
print("=" * 80)

chain_id = 140

with get_connection() as conn:
    with conn.cursor() as cur:
        # チェーン 140 内のすべてのバージョン
        cur.execute("""
            SELECT 
                je.journal_entry_id,
                je.entry_date,
                je.description,
                je.revision_count,
                je.is_latest,
                je.original_entry_id
            FROM journal_entries je
            WHERE (je.journal_entry_id = %s OR je.original_entry_id = %s)
            AND je.is_deleted = false
            ORDER BY je.revision_count ASC
        """, [chain_id, chain_id])
        
        versions = cur.fetchall()
        print(f"\nチェーン内のバージョン: {len(versions)}")
        for row in versions:
            print(f"\n  • ID {row['journal_entry_id']} (v{row['revision_count']}):")
            print(f"    - 日付: {row['entry_date']}")
            print(f"    - 摘要: {row['description'][:60]}...")
            print(f"    - 最新: {row['is_latest']}")
            print(f"    - オリジナル: {row['original_entry_id']}")
        
        # 各バージョンで account_id 19 を持つか確認
        print("\n【各バージョンで account_id 19 を持つか確認】")
        for row in versions:
            cur.execute("""
                SELECT COUNT(*) as cnt
                FROM journal_lines
                WHERE journal_entry_id = %s AND account_id = 19
            """, [row['journal_entry_id']])
            has_account = cur.fetchone()
            print(f"  ID {row['journal_entry_id']}: account_id 19を含む = {has_account['cnt'] > 0}")

        # 期間内（2025-06-01～06-30）で、account_id 19を含むすべてのバージョン
        print("\n【期間内 + account_id 19 フィルター】")
        cur.execute("""
            SELECT 
                je.journal_entry_id,
                je.entry_date,
                je.revision_count,
                je.is_latest
            FROM journal_entries je
            WHERE (je.journal_entry_id = %s OR je.original_entry_id = %s)
            AND je.is_deleted = false
            AND je.entry_date >= %s
            AND je.entry_date <= %s
            AND je.journal_entry_id IN (
                SELECT DISTINCT journal_entry_id
                FROM journal_lines
                WHERE account_id = 19
            )
            ORDER BY je.revision_count ASC
        """, [chain_id, chain_id, '2025-06-01', '2025-06-30'])
        
        filtered = cur.fetchall()
        print(f"\n期間内 + account_id 19 フィルター: {len(filtered)} 件")
        for row in filtered:
            print(f"  • ID {row['journal_entry_id']} (v{row['revision_count']}, latest={row['is_latest']}): {row['entry_date']}")

print("\n" + "=" * 80)
