#!/usr/bin/env python3
import os
import sys
import psycopg2
from psycopg2.extras import RealDictCursor
from datetime import date

# 接続設定
try:
    conn = psycopg2.connect(
        user=os.getenv('DB_USER', 'postgres'),
        password=os.getenv('DB_PASSWORD', 'postgres'),
        host='postgres',
        port='5432',
        database=os.getenv('DB_NAME', 'accounting_db')
    )
except:
    # ローカル接続を試みる
    conn = psycopg2.connect(
        user='postgres',
        password='postgres',
        host='localhost',
        port='5432',
        database='accounting_db'
    )

cur = conn.cursor(cursor_factory=RealDictCursor)

# 検索条件
from_date = '2025-06-01'
to_date = '2025-06-30'
account_id = 501  # 費用金

# 条件1: 修正履歴を含まない（最新版本のみ）
print("=" * 80)
print("【検索条件】")
print(f"  期間: {from_date} ～ {to_date}")
print(f"  科目: {account_id}")
print("=" * 80)

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 
        je.journal_entry_id,
        je.entry_date,
        je.description,
        je.revision_count,
        je.is_latest,
        je.original_entry_id,
        COUNT(DISTINCT jl.account_id) as account_count
    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
    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
    LIMIT 10
"""
cur.execute(sql3, [from_date, to_date])
results3 = cur.fetchall()
print(f"  同じ期間内のすべての仕訳（最初の10件）:")
for row in results3:
    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']}, accts={row['account_count']})")

cur.close()
conn.close()

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