#!/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【 7月和8月的1.4M交易鏈條分析 】\n')
        
        # 获取account_id
        cur.execute("SELECT account_id FROM accounts WHERE account_code = '701'")
        aid = cur.fetchone()['account_id']
        
        # 收集7月和8月可能相關的所有交易Entry ID
        cur.execute("""
            SELECT DISTINCT j.journal_entry_id
            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 >= '2025-07-01'
              AND j.entry_date < '2025-09-01'
              AND j.is_deleted = false
            ORDER BY j.journal_entry_id
        """, (aid,))
        
        all_entries = [row['journal_entry_id'] for row in cur.fetchall()]
        print(f"7月和8月的所有Entry ID: {all_entries}\n")
        
        # 查找可能相關的Entry ID（圍繞358, 361, 359, 362）
        target_ids = [358, 359, 361, 362, 365, 366, 370, 374, 375]  # 預期可能存在的IDs
        
        print('【 檢查可能的修正鏈 】\n')
        
        for month, entries_in_month in [(7, [358, 361]), (8, [359, 362])]:
            print(f"---- {month}月 ----\n")
            
            # 查找这两个entry及其相关的parent/child关系
            cur.execute("""
                SELECT 
                  j.journal_entry_id,
                  j.parent_entry_id,
                  j.description,
                  l.debit,
                  l.credit,
                  (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 = %s
                WHERE j.journal_entry_id IN (%s, %s)
                   OR j.parent_entry_id IN (%s, %s)
                ORDER BY j.journal_entry_id
            """, (aid, entries_in_month[0], entries_in_month[1], entries_in_month[0], entries_in_month[1]))
            
            rows = cur.fetchall()
            if rows:
                print("Entry# | Parent | Debit      | Credit     | HasChild | Desc (first 45 chars)")
                print("-" * 85)
                for row in rows:
                    parent_str = f"#{row['parent_entry_id']}" if row['parent_entry_id'] else "None"
                    debit = row['debit'] or 0
                    credit = row['credit'] or 0
                    desc = row['description'][:45] if row['description'] else ""
                    child_str = "是" if row['has_child'] > 0 else "否"
                    print(f"#{row['journal_entry_id']:<6} | {parent_str:<6} | {debit:>10} | {credit:>10} | {child_str:<8} | {desc}")
            else:
                print("沒有找到相關交易")
            
            print()
        
        print('\n【 當前試算表結果 (各月份) 】\n')
        
        for month in [7, 8]:
            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 >= %s
                  AND j.entry_date < %s
                  AND j.is_deleted = false
                  AND child.journal_entry_id IS NULL
            """, (aid, f'2025-{month:02d}-01', f'2025-{month+1:02d}-01' if month < 12 else '2026-01-01'))
            row = cur.fetchone()
            
            print(f"2025年{month}月:")
            print(f"  借方: {row['debit']:>10}")
            print(f"  貳方: {row['credit']:>10}")
            print()
