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("=" * 120)
print("【删除ID 444后的交叉汇总验证】")
print("=" * 120)

# 计算全体试算表
cur.execute("""
    SELECT 
        COALESCE(SUM(jl.debit), 0) as total_debit,
        COALESCE(SUM(jl.credit), 0) as total_credit
    FROM journal_lines jl
    INNER JOIN journal_entries je ON jl.journal_entry_id = je.journal_entry_id
    WHERE je.is_deleted = false
    AND je.is_latest = true
""")

total_debit, total_credit = cur.fetchone()

print("\n【全体試算表】")
print(f"借方合計: {total_debit:>15,.0f}")
print(f"貸方合計: {total_credit:>15,.0f}")
print(f"差額: {abs(total_debit - total_credit):>15,.0f}")

if abs(total_debit - total_credit) < 1:
    print("✓ バランス完実（完全一致）")
else:
    print("✗ バランス不一致")

# 查询普通預金（科目ID=2）的期末残高
print("\n" + "=" * 120)
print("【普通預金 期末残高】")
print("=" * 120)

cur.execute("""
    SELECT 
        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
""")

balance = cur.fetchone()[0]
print(f"\n現在の期末残高: {balance:>15,.0f}円")

# 同时显示期末残高的借方和貸方分离数字
cur.execute("""
    SELECT 
        COALESCE(SUM(jl.debit), 0) as total_debit,
        COALESCE(SUM(jl.credit), 0) as total_credit
    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
""")

debit, credit = cur.fetchone()
print(f"\n内訳:")
print(f"  借方合計（入金）: {debit:>15,.0f}円")
print(f"  貸方合計（出金）: {credit:>15,.0f}円")
print(f"  差額（残高）: {debit - credit:>15,.0f}円")

# 期望值对比
expected_balance = 14_916_322
print(f"\n期望残高: {expected_balance:>15,.0f}円")
print(f"現在残高: {balance:>15,.0f}円")
print(f"差額: {expected_balance - balance:>15,.0f}円")

cur.close()
conn.close()
