#!/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【 2025年7月和8月的可疑交易（大額）】\n')
        
        # 获取account_id
        cur.execute("SELECT account_id FROM accounts WHERE account_code = '701'")
        aid = cur.fetchone()['account_id']
        
        for month in [7, 8]:
            print(f"\n========== 2025年{month}月 ==========\n")
            
            # 找出所有金額超過500,000的交易
            cur.execute("""
                SELECT 
                  j.journal_entry_id,
                  j.entry_date,
                  j.description,
                  l.debit,
                  l.credit,
                  j.parent_entry_id,
                  j.is_deleted
                FROM journal_lines l
                JOIN journal_entries j ON j.journal_entry_id = l.journal_entry_id
                WHERE l.account_id = %s
                  AND j.entry_date >= %s
                  AND j.entry_date < %s
                  AND (l.debit > 500000 OR l.credit > 500000)
                  AND j.is_deleted = false
                ORDER BY j.entry_date
            """, (aid, f'2025-{month:02d}-01', f'2025-{month+1:02d}-01' if month < 12 else '2026-01-01'))
            
            entries = cur.fetchall()
            print(f"找到 {len(entries)} 筆大額交易:\n")
            
            for row in entries:
                parent_str = f"P#{row['parent_entry_id']}" if row['parent_entry_id'] else "P=None"
                desc = row['description'][:50] if row['description'] else ""
                
                # 簡短顯示
                if row['debit'] > 0:
                    print(f"Entry#{row['journal_entry_id']}: 借{row['debit']:>10} {parent_str:<12} {desc}")
                else:
                    print(f"Entry#{row['journal_entry_id']}: 貳{row['credit']:>10} {parent_str:<12} {desc}")
        
        print('\n\n【 總結分析 】\n')
        print('如果7月/8月也有重複1,400,000的取消交易模式，請確認：')
        print('1. 是否存在無parent的【未計上のため取消】交易（應該被刪除）')
        print('2. 是否存在【修正後】且無子交易的借方（應該被刪除）')
