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

from app.core.database 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:
        # ステップ 1: journal_lines に account_id 501 のレコードがあるか
        print("\n【ステップ 0】account_id 501 を持つ journal_lines")
        sql0 = "SELECT COUNT(*) as cnt FROM journal_lines WHERE account_id = %s"
        cur.execute(sql0, [account_id])
        result0 = cur.fetchone()
        print(f"  全体件数: {result0['cnt']}")

        # ステップ 2: journal_lines に account_id 501 で期間限定のレコードがあるか
        print("\n【ステップ 0.5】account_id 501 で期間限定のレコード")
        sql0_5 = """
            SELECT COUNT(*) as cnt FROM journal_lines jl
            WHERE jl.account_id = %s
            AND jl.journal_entry_id IN (
                SELECT journal_entry_id FROM journal_entries 
                WHERE entry_date >= %s AND entry_date <= %s
            )
        """
        cur.execute(sql0_5, [account_id, from_date, to_date])
        result0_5 = cur.fetchone()
        print(f"  期間内件数: {result0_5['cnt']}")

        # ステップ 3: その journal_entry_id のリスト
        print("\n【ステップ 1】該当する journal_entry_id のリスト")
        sql1 = """
            SELECT DISTINCT journal_entry_id 
            FROM journal_lines 
            WHERE account_id = %s
            AND journal_entry_id IN (
                SELECT journal_entry_id FROM journal_entries 
                WHERE entry_date >= %s AND entry_date <= %s
            )
        """
        cur.execute(sql1, [account_id, from_date, to_date])
        entry_ids = [row['journal_entry_id'] for row in cur.fetchall()]
        print(f"  該当 journal_entry_id: {entry_ids}")

        if entry_ids:
            print("\n【ステップ 2】これらの仕訳の詳細")
            placeholders = ','.join(['%s'] * len(entry_ids))
            sql2 = f"""
                SELECT 
                    journal_entry_id, entry_date, description, revision_count, is_latest
                FROM journal_entries
                WHERE journal_entry_id IN ({placeholders})
            """
            cur.execute(sql2, entry_ids)
            for row in cur.fetchall():
                print(f"    • ID {row['journal_entry_id']}: {row['entry_date']} - {row['description']} (v{row['revision_count']}, latest={row['is_latest']})")

        # オリジナルのクエリ
        print("\n【ステップ 3】修正履歴を含まない（is_latest = true）")
        sql3 = """
            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
                )
        """
        cur.execute(sql3, [from_date, to_date, account_id])
        result3 = cur.fetchone()
        print(f"  件数: {result3['cnt']}")

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