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

import os
import sys

# 添加backend目录到路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend'))

os.environ.setdefault("DB_HOST", "localhost")
os.environ.setdefault("DB_PORT", "5432")
os.environ.setdefault("DB_NAME", "accounting_db")
os.environ.setdefault("DB_USER", "postgres")
os.environ.setdefault("DB_PASSWORD", "root")

from app.core.database import get_connection
from decimal import Decimal

def check_account_701_detailed():
    """详细检查701账户2025年6月的所有交易"""
    
    with get_connection() as conn:
        with conn.cursor() as cur:
            print("=" * 100)
            print("921年6月 账户701(売上高) 详细数据分析")
            print("=" * 100)
            
            # 查询所有相关交易
            sql = """
            SELECT 
                e.journal_entry_id,
                e.entry_date,
                e.description,
                l.account_id,
                a.account_name,
                COALESCE(l.debit, 0) as debit,
                COALESCE(l.credit, 0) as credit,
                e.is_deleted,
                e.parent_entry_id,
                e.version
            FROM journal_lines l
            JOIN journal_entries e ON e.journal_entry_id = l.journal_entry_id
            JOIN accounts a ON a.account_id = l.account_id
            WHERE a.account_id = 701
              AND e.entry_date >= '2025-06-01'
              AND e.entry_date <= '2025-06-30'
            ORDER BY e.entry_date, e.journal_entry_id
            """
            
            cur.execute(sql)
            all_rows = cur.fetchall()
            
            # 分析数据
            total_all_debit = Decimal(0)
            total_all_credit = Decimal(0)
            total_valid_debit = Decimal(0)
            total_valid_credit = Decimal(0)
            
            print("\n【 全部交易 】")
            for row in all_rows:
                total_all_debit += row['debit']
                total_all_credit += row['credit']
                
                status_flags = []
                if row['is_deleted']:
                    status_flags.append("已删除")
                if '[逆仕訳]' in row['description']:
                    status_flags.append("逆仕訳")
                if row['parent_entry_id'] is not None:
                    status_flags.append(f"修正版(原ID:{row['parent_entry_id']})")
                
                status = " | ".join(status_flags) if status_flags else "✓ 有效"
                print(f"ID:{row['journal_entry_id']:5d} | {row['entry_date']} | {row['description']:40s} | " + 
                      f"借:{row['debit']:12} | 贷:{row['credit']:12} | {status}")
            
            print(f"\n全部交易总计 - 借方: {total_all_debit:,} | 贷方: {total_all_credit:,}")
            
            # 查询实际被排除的交易
            print("\n【 需要排除的交易 】")
            
            # 1. 查询被修正的交易
            sql_corrected = """
            SELECT DISTINCT parent_entry_id
            FROM journal_entries
            WHERE parent_entry_id IS NOT NULL
              AND parent_entry_id IN (
                  SELECT journal_entry_id
                  FROM journal_entries
                  WHERE entry_date >= '2025-06-01'
                    AND entry_date <= '2025-06-30'
              )
            """
            
            cur.execute(sql_corrected)
            corrected_ids = [row['parent_entry_id'] for row in cur.fetchall()]
            
            if corrected_ids:
                print(f"已被修正的交易ID: {corrected_ids}")
                sql_corrected_data = """
                SELECT 
                    journal_entry_id,
                    entry_date,
                    description,
                    COALESCE(SUM(l.debit), 0) as total_debit,
                    COALESCE(SUM(l.credit), 0) as total_credit
                FROM journal_lines l
                JOIN journal_entries e ON e.journal_entry_id = l.journal_entry_id
                WHERE e.journal_entry_id IN ({})
                  AND l.account_id = 701
                GROUP BY e.journal_entry_id, e.entry_date, e.description
                """.format(','.join(str(id) for id in corrected_ids))
                
                cur.execute(sql_corrected_data)
                corrected_rows = cur.fetchall()
                for row in corrected_rows:
                    print(f"  ID:{row['journal_entry_id']} | {row['entry_date']} | {row['description']} | " +
                          f"借:{row['total_debit']:,} | 贷:{row['total_credit']:,}")
                    total_valid_credit -= row['total_credit']  # 这些应该被排除
            
            # 2. 查询逆仕訳标记的交易
            sql_reversed = """
            SELECT 
                journal_entry_id,
                entry_date,
                description,
                COALESCE(SUM(l.debit), 0) as total_debit,
                COALESCE(SUM(l.credit), 0) as total_credit
            FROM journal_lines l
            JOIN journal_entries e ON e.journal_entry_id = l.journal_entry_id
            WHERE e.description LIKE '%[逆仕訳]%'
              AND e.entry_date >= '2025-06-01'
              AND e.entry_date <= '2025-06-30'
              AND l.account_id = 701
            GROUP BY e.journal_entry_id, e.entry_date, e.description
            """
            
            cur.execute(sql_reversed)
            reversed_rows = cur.fetchall()
            
            if reversed_rows:
                print("\n标记为逆仕訳的交易:")
                for row in reversed_rows:
                    print(f"  ID:{row['journal_entry_id']} | {row['entry_date']} | {row['description']} | " +
                          f"借:{row['total_debit']:,} | 贷:{row['total_credit']:,}")
                    total_valid_credit -= row['total_credit']
            
            # 计算有效总计
            for row in all_rows:
                # 排除已删除
                if row['is_deleted']:
                    continue
                # 排除逆仕訳
                if '[逆仕訳]' in row['description']:
                    continue
                # 排除被修正的交易
                if row['parent_entry_id'] is not None:
                    continue
                # 排除作为修正元的交易
                if row['journal_entry_id'] in corrected_ids:
                    continue
                
                total_valid_debit += row['debit']
                total_valid_credit += row['credit']
            
            print(f"\n【 有效交易总计 】")
            print(f"借方: {total_valid_debit:,}")
            print(f"贷方: {total_valid_credit:,}")
            print(f"\n差异检查:")
            print(f"全部贷方:   {total_all_credit:,}")
            print(f"有效贷方:   {total_valid_credit:,}")
            print(f"需排除金额: {total_all_credit - total_valid_credit:,}")
            
            if total_all_credit - total_valid_credit == 1400000:
                print("✓ 找到问题！差异正好是1,400,000")

if __name__ == "__main__":
    check_account_701_detailed()
