#!/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('\n【 執行選項A：完全對冲 】\n')
        
        print('操作1: 刪除Entry#371（已完成）')
        print('操作2: 刪除Entry#373（進行中）...\n')
        
        # 標記Entry#373為已刪除
        print('執行: UPDATE journal_entries SET is_deleted=true WHERE journal_entry_id=373')
        cur.execute('UPDATE journal_entries SET is_deleted=true WHERE journal_entry_id = 373')
        conn.commit()
        print('✓ Entry#373 已標記為已刪除\n')
        
        # 驗證修正鏈條都被正確過濾
        print('【 驗證修正鏈條 】\n')
        cur.execute("""
            SELECT
              j.journal_entry_id,
              j.description,
              l.debit,
              l.credit,
              j.parent_entry_id,
              j.is_deleted,
              (SELECT COUNT(*) FROM journal_entries child WHERE child.parent_entry_id = j.journal_entry_id) as has_child
            FROM journal_entries j
            LEFT JOIN journal_lines l ON l.journal_entry_id = j.journal_entry_id AND l.account_id = (
              SELECT account_id FROM accounts WHERE account_code = '701'
            )
            WHERE j.journal_entry_id IN (357, 360, 372, 373)
            ORDER BY j.journal_entry_id
        """)
        
        print("Entry# | Delete | Parent | 借方       | 貳方       | 狀態")
        print("-" * 70)
        for row in cur.fetchall():
            delete_str = "是" if row['is_deleted'] else "否"
            parent_str = f"#{row['parent_entry_id']}" if row['parent_entry_id'] else "None"
            debit = row['debit'] or 0
            credit = row['credit'] or 0
            
            # 確定是否被過濾
            if row['is_deleted']:
                status = "❌ 已刪除"
            elif row['has_child'] > 0:
                status = "❌ 有子(被過濾)"
            else:
                status = "✓ 被計入"
            
            print(f"#{row['journal_entry_id']:<6} | {delete_str:<6} | {parent_str:<6} | {debit:>10} | {credit:>10} | {status}")
        
        print('\n【 最終驗證：試算表結果 】\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}')
        print(f'  淨值 (credit - debit): {row["credit"] - row["debit"]:>10}')
        
        if row['debit'] == 0 and row['credit'] == 4082728:
            print('\n✓✓✓ 完美！對冲成功！')
            print('  - 1,400,000的借貳對冲已完全移除試算表')
            print('  - 貳方金額為淨值: 4,082,728')
        elif row['credit'] == 4082728:
            print(f'\n✓ 貳方正確，但借方仍有：{row["debit"]}')
        else:
            print(f'\n⚠️ 可能還有其他問題，當前值: 借{row["debit"]}, 貳{row["credit"]}')
