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

from app.core.database import get_connection

print("=" * 80)
print("【account_id 19（買掛金）の修正チェーン分析】")
print("=" * 80)

from_date = "2025-06-01"
to_date = "2025-06-30"
account_id = 19

with get_connection() as conn:
    with conn.cursor() as cur:
        # Step 1: account_id 19 を含む仕訳を全て取得
        print("\n【Step 1】account_id 19 を含むすべての仕訳（期間内）")
        cur.execute("""
            SELECT DISTINCT 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.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 = %s
                )
            ORDER BY je.entry_date DESC, je.journal_entry_id DESC
        """, [from_date, to_date, account_id])
        
        all_entries = cur.fetchall()
        print(f"件数: {len(all_entries)}")
        for row in all_entries:
            print(f"  • ID {row['journal_entry_id']}: {row['entry_date']} - {row['description'][:50]}... (v{row['revision_count']}, latest={row['is_latest']}, orig={row['original_entry_id']})")

        # Step 2: 修正チェーンの分析
        print("\n【Step 2】修正チェーンの詳細")
        cur.execute("""
            SELECT 
                COALESCE(je.original_entry_id, je.journal_entry_id) as chain_id,
                array_agg(je.journal_entry_id ORDER BY je.revision_count) as entry_ids,
                array_agg(je.revision_count ORDER BY je.revision_count) as revisions,
                array_agg(je.is_latest ORDER BY je.revision_count) as is_latest_flags,
                MAX(je.revision_count) as max_revision,
                COUNT(*) as version_count
            FROM journal_entries je
            WHERE 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 = %s
                )
            GROUP BY COALESCE(je.original_entry_id, je.journal_entry_id)
            ORDER BY chain_id DESC
        """, [from_date, to_date, account_id])
        
        chains = cur.fetchall()
        print(f"修正チェーン数: {len(chains)}")
        for chain in chains:
            print(f"\n  chain_id {chain['chain_id']}:")
            print(f"    • エントリID: {chain['entry_ids']}")
            print(f"    • リビジョン: {chain['revisions']}")
            print(f"    • 最新フラグ: {chain['is_latest_flags']}")
            print(f"    • バージョン数: {chain['version_count']}, 最大v{chain['max_revision']}")

        # Step 3: 修正履歴を含まない場合と含む場合の件数比較
        print("\n【Step 3】修正履歴フィルター適用の比較")
        
        # without include_history
        cur.execute("""
            SELECT COUNT(*) as cnt
            FROM journal_entries je
            WHERE je.is_deleted = false
                AND je.is_latest = true
                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 = %s
                )
        """, [from_date, to_date, account_id])
        result_without = cur.fetchone()
        print(f"  修正履歴を含まない（is_latest=true）: {result_without['cnt']} 件")
        
        # with include_history
        cur.execute("""
            SELECT COUNT(*) as cnt
            FROM journal_entries je
            WHERE 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 = %s
                )
        """, [from_date, to_date, account_id])
        result_with = cur.fetchone()
        print(f"  修正履歴を含む（すべてのバージョン）: {result_with['cnt']} 件")
        print(f"  差分: {result_with['cnt'] - result_without['cnt']} 件（古いバージョン）")

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