import sys
sys.path.insert(0, '/app')

from app.core.database import get_connection

print("=" * 80)
print("【科目 105 小口現金 と 502 未払金 の確認】")
print("=" * 80)

with get_connection() as conn:
    with conn.cursor() as cur:
        # 科目情報を確認
        print("\n【科目情報】")
        cur.execute("""
            SELECT account_id, account_code, account_name, account_type
            FROM accounts
            WHERE account_id IN (105, 502)
            ORDER BY account_id
        """)
        
        accounts = cur.fetchall()
        for acc in accounts:
            print(f"  • ID {acc['account_id']}: {acc['account_code']} {acc['account_name']} ({acc['account_type']})")

        # 105 を含む journal_lines の件数
        print("\n【105 小口現金 を含む仕訳行】")
        cur.execute("""
            SELECT COUNT(*) as cnt
            FROM journal_lines
            WHERE account_id = 105
        """)
        result = cur.fetchone()
        print(f"  件数: {result['cnt']}")

        if result['cnt'] > 0:
            # 詳細を表示
            print("\n【詳細例（最初の 10 件）】")
            cur.execute("""
                SELECT 
                    jl.journal_line_id,
                    jl.journal_entry_id,
                    je.entry_date,
                    je.description,
                    jl.debit,
                    jl.credit
                FROM journal_lines jl
                JOIN journal_entries je ON jl.journal_entry_id = je.journal_entry_id
                WHERE jl.account_id = 105
                ORDER BY je.entry_date DESC
                LIMIT 10
            """)
            
            for row in cur.fetchall():
                debit_display = f"借方 {row['debit']}" if row['debit'] > 0 else ""
                credit_display = f"貸方 {row['credit']}" if row['credit'] > 0 else ""
                side = (debit_display + " " + credit_display).strip()
                print(f"  • ID {row['journal_line_id']}: {row['entry_date']} - {row['description'][:40]}... ({side})")

        # 102 と比較（参考用）
        print("\n【502 未払金 の現在の利用状況】")
        cur.execute("""
            SELECT COUNT(*) as cnt
            FROM journal_lines
            WHERE account_id = 502
        """)
        result502 = cur.fetchone()
        print(f"  件数: {result502['cnt']}")

print("\n" + "=" * 80)
