import psycopg2

conn = psycopg2.connect(
    host="192.168.0.61",
    port=55432,
    database="njts_acct",
    user="njts_app",
    password="njts_app2025"
)

cur = conn.cursor()

print("=" * 160)
print("【普通預金の詳細確認】")
print("=" * 160)

# 查询普通預金是否有遗漏删除的is_latest=false的记录
cur.execute("""
    SELECT 
        COUNT(*) as total_count,
        SUM(CASE WHEN je.is_deleted = false AND je.is_latest = true THEN 1 ELSE 0 END) as latest_count,
        SUM(CASE WHEN je.is_deleted = false AND je.is_latest = false THEN 1 ELSE 0 END) as old_version_count,
        SUM(CASE WHEN je.is_deleted = true THEN 1 ELSE 0 END) as deleted_count
    FROM journal_lines jl
    INNER JOIN journal_entries je ON jl.journal_entry_id = je.journal_entry_id
    WHERE jl.account_id = 2  -- 普通預金
""")

total, latest, old_ver, deleted = cur.fetchone()
print(f"\n普通預金の仕訳カウント:")
print(f"  全体: {total}")
print(f"  最新版（is_latest=true）: {latest}")
print(f"  古い版（is_deleted=false, is_latest=false）: {old_ver}")
print(f"  削除済み（is_deleted=true）: {deleted}")

# 查询普通預金的各种状态的余额
cur.execute("""
    SELECT 
        je.is_latest,
        je.is_deleted,
        COUNT(*) as cnt,
        COALESCE(SUM(jl.debit), 0) as total_debit,
        COALESCE(SUM(jl.credit), 0) as total_credit,
        COALESCE(SUM(jl.debit), 0) - COALESCE(SUM(jl.credit), 0) as balance
    FROM journal_lines jl
    INNER JOIN journal_entries je ON jl.journal_entry_id = je.journal_entry_id
    WHERE jl.account_id = 2
    GROUP BY je.is_latest, je.is_deleted
    ORDER BY je.is_deleted, je.is_latest
""")

print(f"\n普通預金の状態別残高:")
print()

total_all = 0
for is_latest, is_deleted, cnt, debit, credit, balance in cur.fetchall():
    status = f"is_latest={is_latest}, is_deleted={is_deleted}"
    print(f"  {status:35} | 件数={cnt:3} | 借={debit:>12,.0f}  貸={credit:>12,.0f} | 残高={balance:>12,.0f}円")
    total_all += balance

print(f"\n全て合計: {total_all:>15,.0f}円")

# 查询只计算最新版本和非删除的
cur.execute("""
    SELECT 
        COALESCE(SUM(COALESCE(jl.debit, 0) - COALESCE(jl.credit, 0)), 0)
    FROM journal_lines jl
    INNER JOIN journal_entries je ON jl.journal_entry_id = je.journal_entry_id
    WHERE jl.account_id = 2
    AND je.is_deleted = false
    AND je.is_latest = true
""")

valid_balance = cur.fetchone()[0]
print(f"有効な残高（is_deleted=false, is_latest=true）: {valid_balance:>15,.0f}円")

# 比对
print("\n" + "=" * 160)
print("【理想的な月別普通預金期末残高】")
print("=" * 160)

cur.execute("""
    SELECT 
        EXTRACT(YEAR FROM je.entry_date)::INT as year,
        EXTRACT(MONTH FROM je.entry_date)::INT as month,
        CASE 
            WHEN EXTRACT(MONTH FROM je.entry_date) >= 6 
            THEN EXTRACT(YEAR FROM je.entry_date)
            ELSE EXTRACT(YEAR FROM je.entry_date) - 1
        END as fiscal_year,
        COALESCE(SUM(COALESCE(jl.debit, 0) - COALESCE(jl.credit, 0)), 0) as balance
    FROM journal_lines jl
    INNER JOIN journal_entries je ON jl.journal_entry_id = je.journal_entry_id
    WHERE jl.account_id = 2
    AND je.is_deleted = false
    AND je.is_latest = true
    AND EXTRACT(YEAR FROM je.entry_date) = 2025
    GROUP BY fiscal_year, year, month
    ORDER BY month
""")

results = cur.fetchall()
print()
for year, month, fy, balance in results:
    print(f"  {year}年{month:2}月：{balance:>15,.0f}円")

cur.close()
conn.close()
