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

from app.core.database import get_connection

print("=" * 80)
print("【すべての journal_entry の修正歴チェーン分析】")
print("=" * 80)

with get_connection() as conn:
    with conn.cursor() as cur:
        # すべてのチェーンを取得
        cur.execute("""
            SELECT 
                COALESCE(je.original_entry_id, je.journal_entry_id) as chain_id,
                array_agg(DISTINCT je.journal_entry_id ORDER BY je.journal_entry_id) as all_entry_ids,
                array_agg(DISTINCT je.revision_count ORDER BY je.revision_count DESC) as all_revisions,
                COUNT(*) as total_versions,
                COUNT(CASE WHEN je.is_latest = true THEN 1 END) as latest_count,
                COUNT(CASE WHEN je.is_latest = false THEN 1 END) as old_count,
                MAX(je.revision_count) as max_revision
            FROM journal_entries je
            WHERE je.is_deleted = false
            GROUP BY COALESCE(je.original_entry_id, je.journal_entry_id)
            HAVING COUNT(*) > 1 OR MAX(je.revision_count) > 1
            ORDER BY MAX(je.revision_count) DESC
            LIMIT 20
        """)
        
        chains = cur.fetchall()
        print(f"\n修正チェーン数: {len(chains)}")
        
        if chains:
            print("\n📋 詳細：")
            for i, chain in enumerate(chains, 1):
                print(f"\n{i}. Chain ID {chain['chain_id']}:")
                print(f"     • 全 entry_id: {chain['all_entry_ids']}")
                print(f"     • リビジョン: {chain['all_revisions']}")
                print(f"     • 総バージョン数: {chain['total_versions']}")
                print(f"     • 最新版本: {chain['latest_count']}, 古いバージョン: {chain['old_count']}")
                print(f"     • 最大リビジョン: v{chain['max_revision']}")
        else:
            print("\n⚠️ 修正歴チェーン（複数バージョン）が見つかりません")
            
        # 古いバージョンが存在するか直接確認
        print("\n" + "=" * 80)
        print("【古いバージョン（is_latest = false）の存在確認】")
        cur.execute("""
            SELECT COUNT(*) as old_version_count,
                   COUNT(DISTINCT COALESCE(original_entry_id, journal_entry_id)) as old_chain_count
            FROM journal_entries
            WHERE is_deleted = false AND is_latest = false
        """)
        old_result = cur.fetchone()
        print(f"\n古いバージョン総数: {old_result['old_version_count']}")
        print(f"古いバージョンを含むチェーン数: {old_result['old_chain_count']}")
        
        if old_result['old_version_count'] > 0:
            print("\n📝 古いバージョンの例（最初の 5 個）：")
            cur.execute("""
                SELECT je.journal_entry_id, je.entry_date, je.description, 
                       je.revision_count, je.original_entry_id
                FROM journal_entries je
                WHERE je.is_deleted = false AND je.is_latest = false
                ORDER BY je.journal_entry_id DESC
                LIMIT 5
            """)
            for row in cur.fetchall():
                print(f"  • ID {row['journal_entry_id']}: {row['entry_date']} - v{row['revision_count']} (orig={row['original_entry_id']})")

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