#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Analyze the composition of 2025年6月 売上高 debit 3,310,000
"""
import sys
sys.path.insert(0, '/app')

from app.core.database import get_connection
from datetime import date

def analyze():
    with get_connection() as conn:
        with conn.cursor() as cur:
            print("=" * 80)
            print("【2025年6月 売上高借方 3,310,000 の分析】")
            print("=" * 80)
            print()
            
            # Get account_id for 701
            cur.execute("SELECT account_id FROM accounts WHERE account_code = '701'")
            acc_result = cur.fetchone()
            if not acc_result:
                print("701科目が見つかりません")
                return
            
            account_id = acc_result['account_id']
            
            print("【ステップ1: 2025年6月の売上高借方明細（最新版のみ）】")
            print()
            
            cur.execute("""
                SELECT 
                    j.journal_entry_id,
                    j.description,
                    j.entry_date,
                    j.is_latest,
                    j.created_at,
                    l.debit,
                    l.credit
                FROM journal_lines l
                JOIN journal_entries j ON j.journal_entry_id = l.journal_entry_id
                WHERE l.account_id = %s
                AND EXTRACT(YEAR FROM j.entry_date) = 2025
                AND EXTRACT(MONTH FROM j.entry_date) = 6
                AND j.is_deleted = false
                AND j.is_latest = true
                ORDER BY j.entry_date, j.journal_entry_id
            """, (account_id,))
            
            entries = cur.fetchall()
            total_debit = 0
            total_credit = 0
            
            for i, e in enumerate(entries, 1):
                print(f"{i}. ID={e['journal_entry_id']:4d}: {e['description']:<30s} ({e['entry_date']})")
                print(f"   借={e['debit']:>12.0f}  貸={e['credit']:>12.0f}  is_latest={e['is_latest']}")
                total_debit += e['debit']
                total_credit += e['credit']
            
            print()
            print(f"【合計】借方: {total_debit:>12,.0f}  貸方: {total_credit:>12,.0f}")
            print()
            
            # Double check: also include old versions to see the difference
            print("【ステップ2: 参考 - すべてのバージョン（is_latest無関係）】")
            print()
            
            cur.execute("""
                SELECT 
                    j.journal_entry_id,
                    j.description,
                    j.entry_date,
                    j.is_latest,
                    j.is_deleted,
                    l.debit,
                    l.credit
                FROM journal_lines l
                JOIN journal_entries j ON j.journal_entry_id = l.journal_entry_id
                WHERE l.account_id = %s
                AND EXTRACT(YEAR FROM j.entry_date) = 2025
                AND EXTRACT(MONTH FROM j.entry_date) = 6
                AND j.is_deleted = false
                ORDER BY j.entry_date, j.journal_entry_id
            """, (account_id,))
            
            all_entries = cur.fetchall()
            all_debit = 0
            all_credit = 0
            
            for e in all_entries:
                latest_mark = "✓最新" if e['is_latest'] else "✗旧版"
                print(f"ID={e['journal_entry_id']:4d}: {e['description']:<30s} ({e['entry_date']}) {latest_mark}")
                print(f"      借={e['debit']:>12,.0f}  貸={e['credit']:>12,.0f}")
                all_debit += e['debit']
                all_credit += e['credit']
            
            print()
            if all_debit != total_debit:
                print(f"【注意】すべてのバージョン: 借方={all_debit:>12,.0f}  貸方={all_credit:>12,.0f}")
                print(f"           最新版のみ: 借方={total_debit:>12,.0f}  貸方={total_credit:>12,.0f}")
                print(f"           差分: 借方={all_debit - total_debit:>12,.0f}（古い版の分）")
            else:
                print(f"✓ 最新版のみのデータ = すべてのバージョン（修正なし）")
            
            print()
            print("【ステップ3: 修正チェーンの確認】")
            
            # Check if any of these entries are part of a correction chain
            cur.execute("""
                SELECT DISTINCT 
                    COALESCE(j.original_entry_id, j.journal_entry_id) as chain_id,
                    COUNT(*) as count_in_chain
                FROM journal_entries j
                WHERE j.journal_entry_id IN (
                    SELECT DISTINCT l.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 EXTRACT(YEAR FROM j.entry_date) = 2025
                    AND EXTRACT(MONTH FROM j.entry_date) = 6
                    AND j.is_deleted = false
                )
                GROUP BY COALESCE(j.original_entry_id, j.journal_entry_id)
                HAVING COUNT(*) > 1
            """, (account_id,))
            
            chains = cur.fetchall()
            if chains:
                print("修正チェーンが見つかりました:")
                for chain in chains:
                    print(f"  Chain {chain['chain_id']}: {chain['count_in_chain']} バージョン")
            else:
                print("修正チェーンなし（すべて単独のバージョン）")

if __name__ == "__main__":
    try:
        analyze()
    except Exception as e:
        print(f"エラー: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
