import psycopg2
from psycopg2.extras import RealDictCursor

conn = psycopg2.connect('host=192.168.0.61 port=55432 dbname=njts_acct user=njts_app password=njts_app2025')
cur = conn.cursor(cursor_factory=RealDictCursor)

print("=" * 80)
print("7月/8月のEntry parent_entry_id 修復")
print("=" * 80)

# 7月修復：Entry#361 の parent_entry_id を 358 に設定
print("\n【7月の修復】")
print("Before: Entry#361.parent_entry_id = None")
cur.execute("UPDATE journal_entries SET parent_entry_id = 358 WHERE journal_entry_id = 361")
print("After:  Entry#361.parent_entry_id = 358 ✓")

# 8月修復：Entry#362 の parent_entry_id を 359 に設定
print("\n【8月の修復】")
print("Before: Entry#362.parent_entry_id = None")
cur.execute("UPDATE journal_entries SET parent_entry_id = 359 WHERE journal_entry_id = 362")
print("After:  Entry#362.parent_entry_id = 359 ✓")

conn.commit()

# 修復結果を確認
print("\n" + "=" * 80)
print("修復結果の確認")
print("=" * 80)

cur.execute('''
SELECT 
  je.journal_entry_id,
  je.entry_date,
  je.parent_entry_id,
  je.description,
  SUM(CASE WHEN jl.debit::numeric > 0 THEN jl.debit::numeric ELSE 0 END) as total_debit,
  SUM(CASE WHEN jl.credit::numeric > 0 THEN jl.credit::numeric ELSE 0 END) as total_credit
FROM journal_entries je
LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
WHERE je.journal_entry_id IN (358, 361, 359, 362)
  AND je.is_deleted = false
GROUP BY je.journal_entry_id, je.entry_date, je.parent_entry_id, je.description
ORDER BY je.journal_entry_id
''')

rows = cur.fetchall()
for row in rows:
    parent_str = f"parent={row['parent_entry_id']}" if row['parent_entry_id'] else "parent=None"
    debit = row['total_debit'] if row['total_debit'] else 0
    credit = row['total_credit'] if row['total_credit'] else 0
    print(f"\nEntry#{row['journal_entry_id']}: {row['entry_date']} | {parent_str}")
    print(f"  Description: {row['description']}")
    print(f"  合計: 借: {debit:,.0f}, 貳: {credit:,.0f}")

conn.close()
print("\n" + "=" * 80)
print("修復完了！✓")
print("=" * 80)
