#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
sys.path.insert(0, 'backend')

os.environ['DB_HOST'] = '192.168.0.61'
os.environ['DB_NAME'] = 'njts_acct'
os.environ['DB_USER'] = 'njts_app'
os.environ['DB_PASSWORD'] = 'njts_app2025'
os.environ['DB_PORT'] = '55432'

from app.core.database import get_connection

with get_connection() as conn:
    with conn.cursor() as cur:
        print('【 刪除重複的Entry#371 】\n')
        
        # 方案1: 標記為已刪除
        print('執行: UPDATE journal_entries SET is_deleted=true WHERE journal_entry_id=371')
        cur.execute('UPDATE journal_entries SET is_deleted=true WHERE journal_entry_id = 371')
        conn.commit()
        print('✓ Entry#371 已標記為已刪除\n')
        
        # 驗證
        print('【 驗證結果 】\n')
        cur.execute("SELECT account_id FROM accounts WHERE account_code = '701'")
        aid = cur.fetchone()['account_id']
        
        cur.execute("""
            SELECT
                COALESCE(SUM(l.debit), 0)  AS debit,
                COALESCE(SUM(l.credit), 0) AS credit
            FROM journal_lines l
            JOIN journal_entries j
                ON j.journal_entry_id = l.journal_entry_id
            LEFT JOIN journal_entries child
                ON child.parent_entry_id = j.journal_entry_id
            WHERE l.account_id = %s
              AND j.entry_date BETWEEN '2025-06-01' AND '2025-06-30'
              AND j.is_deleted = false
              AND child.journal_entry_id IS NULL
        """, (aid,))
        row = cur.fetchone()
        
        print(f'2025年6月 - 科目701（売上高）:')
        print(f'  借方 (debit):  {row["debit"]:>10}')
        print(f'  貳方 (credit): {row["credit"]:>10}')
        
        if row['credit'] == 4082728:
            print('\n✓✓✓ 完美！貳方金額已恢復正確值 4,082,728')
        else:
            print(f'\n⚠️ 仍有差異，當前值：{row["credit"]}')
