#!/usr/bin/env python3
"""
フロントエンドの検索結果と実際のDB内容を比較
"""
import sys
sys.path.insert(0, '/app')

from app.db import get_connection

from_date = '2025-06-01'
to_date = '2025-06-30'
account_id = 501

print("=" * 80)
print("【検索条件】")
print(f"  期間: {from_date} ～ {to_date}")
print(f"  科目: {account_id} (費用金)")
print("=" * 80)

with get_connection() as conn:
    with conn.cursor() as cur:
        # 修正履歴を含まない（最新版本のみ）
        print("\n【1】修正履歴を含まない（is_latest = true）")
        sql1 = """
            SELECT 
                je.journal_entry_id,
                je.entry_date,
                je.description,
                je.revision_count,
                je.is_latest,
                COALESCE(SUM(jl.debit), 0) as debit_total,
                COALESCE(SUM(jl.credit), 0) as credit_total
            FROM journal_entries je
            LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
            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
                )
            GROUP BY je.journal_entry_id, je.entry_date, je.description, je.revision_count, je.is_latest
            ORDER BY je.entry_date DESC, je.journal_entry_id DESC
        """
        cur.execute(sql1, [from_date, to_date, account_id])
        results1 = cur.fetchall()
        print(f"  件数: {len(results1)}")
        for row in results1:
            print(f"    • ID {row['journal_entry_id']}: {row['entry_date']} - {row['description']} (v{row['revision_count']}, latest={row['is_latest']})")

        # 修正履歴を含む（すべてのバージョン）
        print("\n【2】修正履歴を含む（すべてのバージョン）")
        sql2 = """
            SELECT 
                je.journal_entry_id,
                je.entry_date,
                je.description,
                je.revision_count,
                je.is_latest,
                je.original_entry_id,
                COALESCE(SUM(jl.debit), 0) as debit_total,
                COALESCE(SUM(jl.credit), 0) as credit_total
            FROM journal_entries je
            LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
            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 je.journal_entry_id, je.entry_date, je.description, je.revision_count, je.is_latest, je.original_entry_id
            ORDER BY je.entry_date DESC, je.journal_entry_id DESC
        """
        cur.execute(sql2, [from_date, to_date, account_id])
        results2 = cur.fetchall()
        print(f"  件数: {len(results2)}")
        for row in results2:
            print(f"    • ID {row['journal_entry_id']}: {row['entry_date']} - {row['description']} (v{row['revision_count']}, latest={row['is_latest']}, orig={row['original_entry_id']})")

        # 修正チェーンの分析
        print("\n【3】修正チェーンの詳細分析")
        sql3 = """
            SELECT 
                COALESCE(je.original_entry_id, je.journal_entry_id) as chain_id,
                COUNT(*) as version_count,
                STRING_AGG(DISTINCT je.journal_entry_id::text, ', ') as entry_ids,
                STRING_AGG(DISTINCT je.revision_count::text, ', ' ORDER BY je.revision_count::text DESC) as revisions,
                MAX(je.revision_count) as max_revision
            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
        """
        cur.execute(sql3, [from_date, to_date, account_id])
        chains = cur.fetchall()
        print(f"  チェーン数: {len(chains)}")
        for chain in chains:
            print(f"    • Chain {chain['chain_id']}: {chain['version_count']} バージョン (IDs: {chain['entry_ids']}, v{chain['revisions']})")

print("\n" + "=" * 80)
print("✓ 分析完了")
print("=" * 80)
