import psycopg2

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

cur = conn.cursor()

# 删除 ID 445
print("=" * 100)
print("ID=445 の削除処理開始")
print("=" * 100)

entry_id = 445

# 確認
cur.execute("""
    SELECT journal_entry_id, entry_date, description, is_latest, is_deleted
    FROM journal_entries 
    WHERE journal_entry_id = %s
""", (entry_id,))

result = cur.fetchone()
if result:
    entry_id_val, entry_date, description, is_latest, is_deleted = result
    print(f"\n削除対象:")
    print(f"  ID: {entry_id_val}")
    print(f"  日付: {entry_date}")
    print(f"  摘要: {description}")
    print(f"  is_latest: {is_latest}")
    print(f"  is_deleted: {is_deleted}")

# 明細行の確認
cur.execute("""
    SELECT account_id, debit, credit
    FROM journal_lines
    WHERE journal_entry_id = %s
""", (entry_id,))

lines = cur.fetchall()
print(f"\n  明細行（{len(lines)}行）:")
for account_id, debit, credit in lines:
    print(f"    - account_id={account_id}: 借={debit}, 貸={credit}")

# 削除処理
print("\n削除実行中...")

# journal_lines を削除
cur.execute("DELETE FROM journal_lines WHERE journal_entry_id = %s", (entry_id,))
lines_deleted = cur.rowcount
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
print(f"  ✓ journal_entries 削除: {entries_deleted}件")

conn.commit()

print("\n✅ 削除完了！")
print(f"  合計削除: {entries_deleted}仕訳, {lines_deleted}行")

# 削除後の確認
cur.execute("""
    SELECT COUNT(*) as cnt
    FROM journal_entries 
    WHERE journal_entry_id = %s
""", (entry_id,))

verify = cur.fetchone()
if verify[0] == 0:
    print(f"\n✓ ID {entry_id} は完全に削除されました")

cur.close()
conn.close()
