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

import os
import sys

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 diagnose():
    """診断スクリプト"""
    
    with get_connection() as conn:
        with conn.cursor() as cur:
            print("=" * 100)
            print("診断: 2025年6月の701の1,400,000円を探す")
            print("=" * 100)
            
            # 全交易を見る
            print("\n【 全トランザクション 】")
            sql = """
            SELECT 
                e.journal_entry_id,
                e.entry_date,
                e.description,
                l.credit,
                e.is_deleted,
                e.parent_entry_id
            FROM journal_lines l
            JOIN journal_entries e ON e.journal_entry_id = l.journal_entry_id
            WHERE l.account_id = 701
              AND e.entry_date >= '2025-06-01'
              AND e.entry_date <= '2025-06-30'
              AND l.credit > 0
            ORDER BY e.entry_date, e.journal_entry_id
            """
            
            cur.execute(sql)
            rows = cur.fetchall()
            
            total_credit = Decimal(0)
            for row in rows:
                print(f"ID:{row['journal_entry_id']:5d} | {row['entry_date']} | {row['description'][:40]:40s} | " +
                      f"credit:{row['credit']:>12,.0f} | deleted:{row['is_deleted']} | parent:{row['parent_entry_id']}")
                total_credit += row['credit']
            
            print(f"\n全合計: {total_credit:,.0f}")
            
            # [逆仕訳]パターンをテスト
            print("\n【 逆仕訳の検出複数パターンテスト 】")
            
            patterns = [
                ("%[逆仕訳]%", "LIKE '%[逆仕訳]%'"),
                ("[逆仕訳]%", "LIKE '[逆仕訳]%'"),
                ("\\[逆仕訳\\]%", "SIMILAR TO '\\[逆仕訳\\]%'"),
            ]
            
            for pattern, desc in patterns:
                if "SIMILAR" in desc:
                    sql = f"""
                    SELECT COUNT(*) as cnt, COALESCE(SUM(l.credit), 0) as credit
                    FROM journal_lines l
                    JOIN journal_entries e ON e.journal_entry_id = l.journal_entry_id
                    WHERE l.account_id = 701
                      AND e.entry_date >= '2025-06-01'
                      AND e.entry_date <= '2025-06-30'
                      AND e.description SIMILAR TO %s
                    """
                else:
                    sql = f"""
                    SELECT COUNT(*) as cnt, COALESCE(SUM(l.credit), 0) as credit
                    FROM journal_lines l
                    JOIN journal_entries e ON e.journal_entry_id = l.journal_entry_id
                    WHERE l.account_id = 701
                      AND e.entry_date >= '2025-06-01'
                      AND e.entry_date <= '2025-06-30'
                      AND e.description LIKE %s
                    """
                
                cur.execute(sql, (pattern,))
                result = cur.fetchone()
                print(f"{desc:35s} -> cnt:{result['cnt']:2d}, credit:{result['credit']:>12,.0f}")
            
            # 1,400,000の交易を特定
            print("\n【 1,400,000円を探す 】")
            sql = """
            SELECT 
                e.journal_entry_id,
                e.entry_date,
                e.description,
                COALESCE(SUM(l.credit), 0) as total_credit,
                e.is_deleted,
                e.parent_entry_id,
                e.description LIKE '%[逆仕訳]%' as like_pattern,
                e.description SIMILAR TO '%逆仕%' as contains_gyo,
                e.description SIMILAR TO '\\[逆仕訳\\]%' as similar_pattern
            FROM journal_lines l
            JOIN journal_entries e ON e.journal_entry_id = l.journal_entry_id
            WHERE l.account_id = 701
              AND e.entry_date >= '2025-06-01'
              AND e.entry_date <= '2025-06-30'
            GROUP BY e.journal_entry_id, e.entry_date, e.description, e.is_deleted, e.parent_entry_id
            HAVING COALESCE(SUM(l.credit), 0) = 1400000
            """
            
            cur.execute(sql)
            result = cur.fetchone()
            
            if result:
                print(f"見つかりました！")
                print(f"  ID: {result['journal_entry_id']}")
                print(f"  日付: {result['entry_date']}")
                print(f"  説明: {result['description']}")
                print(f"  クレジット: {result['total_credit']:,}")
                print(f"  削除済み: {result['is_deleted']}")
                print(f"  親ID: {result['parent_entry_id']}")
                print(f"  LIKE結果: {result['like_pattern']}")
                print(f"  SIMILAR含む逆仕: {result['contains_gyo']}")
                print(f"  SIMILAR正規表現: {result['similar_pattern']}")
            else:
                print("1,400,000円のクレジット交易は見つかりません")
                
                # 他の額を見る
                print("\n【 クレジット額の分布 】")
                sql = """
                SELECT COALESCE(SUM(l.credit), 0) as total_credit, COUNT(*) as cnt
                FROM journal_lines l
                JOIN journal_entries e ON e.journal_entry_id = l.journal_entry_id
                WHERE l.account_id = 701
                  AND e.entry_date >= '2025-06-01'
                  AND e.entry_date <= '2025-06-30'
                GROUP BY e.journal_entry_id
                ORDER BY total_credit DESC
                LIMIT 10
                """
                
                cur.execute(sql)
                for row in cur.fetchall():
                    print(f"  {row['total_credit']:>12,.0f}")

if __name__ == "__main__":
    diagnose()
