import os
os.environ['DB_HOST'] = '192.168.0.61'
os.environ['DB_PORT'] = '55432'
os.environ['DB_NAME'] = 'njts_acct'
os.environ['DB_USER'] = 'njts_app'
os.environ['DB_PASSWORD'] = 'njts_app2025'

from app.core.database import get_connection

with get_connection() as conn:
    with conn.cursor() as cur:
        print("=== 6月の普通預金（102）仕訳 ===")
        cur.execute("""
            SELECT 
                je.journal_entry_id,
                je.entry_date,
                je.description,
                je.parent_entry_id,
                jl.debit,
                jl.credit
            FROM journal_entries je
            JOIN journal_lines jl ON jl.journal_entry_id = je.journal_entry_id
            JOIN accounts a ON a.account_id = jl.account_id
            WHERE je.entry_date BETWEEN '2025-06-01' AND '2025-06-30'
            AND a.account_code = '102'
            ORDER BY je.journal_entry_id
        """)
        
        rows = cur.fetchall()
        for row in rows:
            print(f"ID: {row['journal_entry_id']:4d}, Parent: {str(row['parent_entry_id']):4s}, "
                  f"Debit: {row['debit']:6.0f}, Credit: {row['credit']:6.0f}, "
                  f"Desc: {row['description'][:50]}")
        
        print("\n=== 試算表クエリでの除外状況 ===")
        cur.execute("""
            SELECT 
                je.journal_entry_id,
                je.description,
                child.journal_entry_id as has_child,
                jl.debit,
                jl.credit,
                CASE 
                    WHEN je.description LIKE '[逆仕訳]%%' THEN '除外:逆仕訳'
                    WHEN child.journal_entry_id IS NOT NULL THEN '除外:親仕訳'
                    ELSE '計上'
                END as status
            FROM journal_entries je
            JOIN journal_lines jl ON jl.journal_entry_id = je.journal_entry_id
            LEFT JOIN journal_entries child ON child.parent_entry_id = je.journal_entry_id
            JOIN accounts a ON a.account_id = jl.account_id
            WHERE je.entry_date BETWEEN '2025-06-01' AND '2025-06-30'
            AND a.account_code = '102'
            AND je.is_deleted = false
            ORDER BY je.journal_entry_id
        """)
        
        rows = cur.fetchall()
        total_debit = 0
        total_credit = 0
        for row in rows:
            status = row['status']
            if status == '計上':
                total_debit += float(row['debit'])
                total_credit += float(row['credit'])
            print(f"ID: {row['journal_entry_id']:4d}, Status: {status:12s}, "
                  f"Debit: {row['debit']:6.0f}, Credit: {row['credit']:6.0f}, "
                  f"Desc: {row['description'][:40]}")
        
        print(f"\n計上される借方合計: {total_debit:.0f}")
        print(f"計上される貸方合計: {total_credit:.0f}")
