import psycopg2

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

cur = conn.cursor()

# 查询 2025年6月到8月 普通預金(acc 2)的试算表余额
cur.execute("""
    SELECT 
        je.entry_date,
        SUM(CASE WHEN jl.debit > 0 THEN jl.debit ELSE 0 END) as debit_total,
        SUM(CASE WHEN jl.credit > 0 THEN jl.credit ELSE 0 END) as credit_total
    FROM journal_entries je
    LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
    WHERE je.entry_date >= '2025-06-01' 
      AND je.entry_date <= '2025-08-31'
      AND jl.account_id = 2
      AND je.is_deleted = false
      AND je.is_latest = true
    GROUP BY je.entry_date
    ORDER BY je.entry_date DESC
""")

results = cur.fetchall()

print("=" * 100)
print("普通預金(102) 2025年6月～8月 試算表用のデータ")
print("=" * 100)

total_debit = 0
total_credit = 0

if results:
    for entry_date, debit, credit in results:
        debit = debit or 0
        credit = credit or 0
        total_debit += debit
        total_credit += credit
        print(f"{entry_date} | 借={debit:>15,.0f}  貸={credit:>15,.0f}")

print(f"\n合計: 借={total_debit:>15,.0f}  貸={total_credit:>15,.0f}")
print(f"期末残高: {total_debit - total_credit:>15,.0f}")

# 確認期待値
expected_balance = 14916322
actual_balance = total_debit - total_credit

print(f"\n期待値: {expected_balance:>15,.0f}")
print(f"実績値: {actual_balance:>15,.0f}")
print(f"差額:   {abs(expected_balance - actual_balance):>15,.0f}")

if abs(expected_balance - actual_balance) < 1:
    print("\n✅ 正常化されました！")
else:
    print(f"\n⚠️  差異があります: {expected_balance - actual_balance:,.0f}")

cur.close()
conn.close()
