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)

delete_list = [
    (143, "2025-07-01", "短期贷付金 返却"),
    (261, "2025-07-05", "FamilyMart 錦糸町店 印刷代"),
    (262, "2025-07-05", "FamilyMart 錦糸町店 印刷代"),
]

print("\n开始删除以下记录:\n")

total_deleted_lines = 0
total_deleted_entries = 0

for entry_id, date, description in delete_list:
    print(f"删除 ID={entry_id} | {date} | {description}")
    
    # 先删除journal_lines
    cur.execute("DELETE FROM journal_lines WHERE journal_entry_id = %s", (entry_id,))
    lines_deleted = cur.rowcount
    total_deleted_lines += lines_deleted
    print(f"  ✓ journal_lines: {lines_deleted}行删除")
    
    # 再删除journal_entries
    cur.execute("DELETE FROM journal_entries WHERE journal_entry_id = %s", (entry_id,))
    entries_deleted = cur.rowcount
    total_deleted_entries += entries_deleted
    print(f"  ✓ journal_entries: {entries_deleted}件删除")
    print()

conn.commit()

print("=" * 160)
print("【验证删除】")
print("=" * 160)

# 验证删除
print("\n验证已删除的IDs是否还存在:\n")

all_deleted = True
for entry_id, date, description in delete_list:
    cur.execute("SELECT COUNT(*) FROM journal_entries WHERE journal_entry_id = %s", (entry_id,))
    cnt = cur.fetchone()[0]
    if cnt == 0:
        print(f"ID={entry_id} ✓ 确认删除")
    else:
        print(f"ID={entry_id} ✗ 未删除！")
        all_deleted = False

print("\n" + "=" * 160)
print("【试算表验证】")
print("=" * 160)

# 验证试算表平衡
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(f"\n借方合計: {total_debit:>15,.0f}円")
print(f"貸方合計: {total_credit:>15,.0f}円")

if abs(total_debit - total_credit) < 1:
    print("✓ 試算表平衡（バランス完実）")
else:
    print(f"✗ 試算表不平衡（差額: {abs(total_debit - total_credit):,.0f}円）")

# 查询普通預金期末残高
print("\n" + "=" * 160)
print("【普通預金 期末残高】")
print("=" * 160)

cur.execute("""
    SELECT 
        COALESCE(SUM(COALESCE(jl.debit, 0) - COALESCE(jl.credit, 0)), 0) as balance,
        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
""")

balance, debit, credit = cur.fetchone()

print(f"\n普通預金期末残高: {balance:>15,.0f}円")
print(f"  入金（借方）: {debit:>15,.0f}円")
print(f"  出金（貸方）: {credit:>15,.0f}円")

expected = 14_916_322
print(f"\n期望値:      {expected:>15,.0f}円")
print(f"現在値:      {balance:>15,.0f}円")
print(f"差額:        {expected - balance:>15,.0f}円")

if balance == expected:
    print("\n✓ 完美达到期望值！")
elif balance < expected:
    print(f"\n⚠ 仍低于期望値 {expected - balance:,}円")
    print("  建议再次检查是否有其他需要删除的数据，或检查是否有遗漏的入金记录")
else:
    print(f"\n⚠ 高于期望値 {balance - expected:,}円")

print("\n" + "=" * 160)
print("【操作完成】")
print("=" * 160)
print(f"\n✓ 共删除 {total_deleted_entries} 件仕訳（{total_deleted_lines} 行明細）")
if all_deleted:
    print("✓ 所有记录已成功删除")
else:
    print("✗ 部分记录删除失败")

cur.close()
conn.close()
