from app.core.database import get_connection

with get_connection() as conn, conn.cursor() as cur:
    # 普通預金(102)の6月の仕訳を確認
    cur.execute('''
        SELECT 
            je.journal_entry_id,
            je.entry_date,
            je.description,
            je.parent_entry_id,
            jl.debit,
            jl.credit,
            CASE WHEN child.journal_entry_id IS NOT NULL THEN 'Y' ELSE 'N' END as has_child
        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
        WHERE jl.account_id = (SELECT account_id FROM accounts WHERE account_code = '102')
          AND je.entry_date BETWEEN '2025-06-01' AND '2025-06-30'
          AND je.is_deleted = false
        ORDER BY je.journal_entry_id
    ''')
    rows = cur.fetchall()
    
    print('ID\t日付\t\t説明\t\t\t\t\tparent\t借方\t\t貸方\t\tchild?')
    print('='*120)
    for r in rows:
        desc = r['description'][:40].ljust(40)
        parent = str(r['parent_entry_id']) if r['parent_entry_id'] else '-'
        print(f"{r['journal_entry_id']}\t{r['entry_date']}\t{desc}\t{parent}\t{r['debit']}\t{r['credit']}\t{r['has_child']}")
    
    print('\n集計（child=Nのみ）:')
    cur.execute('''
        SELECT 
            SUM(jl.debit) as total_debit,
            SUM(jl.credit) as total_credit
        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
        WHERE jl.account_id = (SELECT account_id FROM accounts WHERE account_code = '102')
          AND je.entry_date BETWEEN '2025-06-01' AND '2025-06-30'
          AND je.is_deleted = false
          AND child.journal_entry_id IS NULL
    ''')
    result = cur.fetchone()
    print(f"借方: {result['total_debit']}, 貸方: {result['total_credit']}")
