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

# 接続設定
conn = psycopg2.connect(
    user=os.getenv('DB_USER', 'postgres'),
    password=os.getenv('DB_PASSWORD', 'postgres'),
    host='localhost',
    port='5432',
    database=os.getenv('DB_NAME', 'accounting_db')
)

cur = conn.cursor(cursor_factory=RealDictCursor)

# 修正版本（revision_count > 1）があるか確認
cur.execute("""
    SELECT COUNT(*) as total, 
           COUNT(CASE WHEN is_latest = true THEN 1 END) as latest_count,
           COUNT(CASE WHEN revision_count > 1 THEN 1 END) as revised_count,
           MAX(revision_count) as max_revision
    FROM journal_entries
    WHERE is_deleted = false
""")

result = cur.fetchone()
print("📊 修正版本統計")
print(f"  • 全記録: {result['total']}")
print(f"  • 最新版本: {result['latest_count']}")
print(f"  • 修正版本: {result['revised_count']}")
print(f"  • 最大改版數: {result['max_revision']}")

# 修正版本の例を表示
if result['revised_count'] > 0:
    print("\n📝 修正版本の例（最初の 5 件）：")
    cur.execute("""
        SELECT journal_entry_id, entry_date, description, revision_count, is_latest
        FROM journal_entries
        WHERE revision_count > 1 AND is_deleted = false
        ORDER BY revision_count DESC, journal_entry_id DESC
        LIMIT 5
    """)
    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']})")

cur.close()
conn.close()
