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#361, #362 を削除（6月の修復方法と同じ）")
print("=" * 80)

# 7月削除：Entry#361 を is_deleted=true に設定
print("\n【7月の削除】")
print("Before: Entry#361.is_deleted = false")
cur.execute("UPDATE journal_entries SET is_deleted = true WHERE journal_entry_id = 361")
print("After:  Entry#361.is_deleted = true ✓")

# 8月削除：Entry#362 を is_deleted=true に設定
print("\n【8月の削除】")
print("Before: Entry#362.is_deleted = false")
cur.execute("UPDATE journal_entries SET is_deleted = true WHERE journal_entry_id = 362")
print("After:  Entry#362.is_deleted = true ✓")

conn.commit()

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

for month, year in [(6, 2025), (7, 2025), (8, 2025)]:
    cur.execute('''
SELECT 
  SUM(CASE WHEN jl.debit::numeric > 0 THEN jl.debit::numeric ELSE 0 END) as debit_total,
  SUM(CASE WHEN jl.credit::numeric > 0 THEN jl.credit::numeric ELSE 0 END) as credit_total
FROM journal_lines jl
JOIN journal_entries je ON jl.journal_entry_id = je.journal_entry_id
LEFT JOIN journal_entries child ON child.parent_entry_id = je.journal_entry_id
WHERE jl.account_id = 41  -- 売上高
  AND EXTRACT(YEAR FROM je.entry_date) = %s
  AND EXTRACT(MONTH FROM je.entry_date) = %s
  AND je.is_deleted = false
  AND child.journal_entry_id IS NULL
''', (year, month))
    
    result = cur.fetchone()
    debit = result['debit_total'] if result['debit_total'] else 0
    credit = result['credit_total'] if result['credit_total'] else 0
    
    print(f"\n{year}年{month:2d}月: 借: {debit:>12,.0f} | 貳: {credit:>12,.0f}")

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