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

from app.core.database import get_connection

print("=" * 80)
print("【実際に API が使用している SQL クエリを再現】")
print("=" * 80)

from_date = "2025-06-01"
to_date = "2025-06-30"
account_id = 501
include_history = False

with get_connection() as conn:
    with conn.cursor() as cur:
        # フィールド存在チェック
        cur.execute("""
            SELECT column_name FROM information_schema.columns 
            WHERE table_name = 'journal_entries' 
            AND column_name IN ('is_latest', 'revision_count', 'original_entry_id')
        """)
        existing_fields = {row['column_name'] for row in cur.fetchall()}
        print(f"\n📋 DB フィールド: {existing_fields}")
        
        if 'revision_count' in existing_fields and 'is_latest' in existing_fields:
            if include_history:
                sql = """
                    SELECT 
                        je.journal_entry_id,
                        je.entry_date,
                        je.description,
                        je.fiscal_year,
                        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,
                        STRING_AGG(DISTINCT CASE WHEN jl.tax_rate IS NOT NULL THEN jl.tax_rate::text END, ', ') as tax_rates
                    FROM journal_entries je
                    LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
                    WHERE je.is_deleted = false
                """
            else:
                sql = """
                    SELECT 
                        je.journal_entry_id,
                        je.entry_date,
                        je.description,
                        je.fiscal_year,
                        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,
                        STRING_AGG(DISTINCT CASE WHEN jl.tax_rate IS NOT NULL THEN jl.tax_rate::text END, ', ') as tax_rates
                    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
                """
            params = []
        
        # 期間フ
        sql += " AND je.entry_date >= %s"
        params.append(from_date)
        
        sql += " AND je.entry_date <= %s"
        params.append(to_date)
        
        # account_id フィルター
        if account_id:
            sql += """ AND je.journal_entry_id IN (
                SELECT DISTINCT journal_entry_id 
                FROM journal_lines 
                WHERE account_id = %s
            )"""
            params.append(account_id)
        
        sql += " GROUP BY je.journal_entry_id, je.entry_date, je.description, je.fiscal_year, je.revision_count, je.is_latest, je.original_entry_id"
        sql += " ORDER BY je.entry_date DESC, je.journal_entry_id DESC"
        
        print(f"\n【SQL】")
        print(sql)
        print(f"\n【パラメータ】{params}")
        
        cur.execute(sql, params)
        rows = cur.fetchall()
        
        print(f"\n【結果】{len(rows)} 件")
        for i, row in enumerate(rows, 1):
            print(f"\n{i}. ID {row['journal_entry_id']}")
            print(f"   日付: {row['entry_date']}")
            print(f"   摘要: {row['description']}")
            print(f"   借方: {row['debit_total']}, 貸方: {row['credit_total']}")

        # account_id 501 のレコードを持つ仕訳を確認
        print("\n" + "=" * 80)
        print("【仕訳に含まれる科目の内訳】")
        if rows:
            for row in rows[:1]:  # 最初のレコードが 501 を含むか
                print(f"\n仕訳 ID {row['journal_entry_id']} の行科目:")
                cur.execute("""
                    SELECT account_id, account_name, debit, credit
                    FROM journal_lines jl
                    JOIN accounts a ON jl.account_id = a.account_id
                    WHERE jl.journal_entry_id = %s
                """, [row['journal_entry_id']])
                for line in cur.fetchall():
                    print(f"  • {line['account_id']} {line['account_name']}: 借方 {line['debit']}, 貸方 {line['credit']}")

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