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'

import sys
sys.path.insert(0, os.path.dirname(__file__))

from app.core.database import get_connection

conn = get_connection()
cur = conn.cursor()

# 社会保険料関連の仕訳を確認
print("\n=== 2025年4月 社会保険料の仕訳チェーン ===")
cur.execute("""
    SELECT 
        je.journal_entry_id,
        je.entry_date,
        je.description,
        je.parent_entry_id,
        je.is_deleted,
        CASE 
            WHEN EXISTS (SELECT 1 FROM journal_entries child WHERE child.parent_entry_id = je.journal_entry_id)
            THEN 'Y' ELSE 'N'
        END as has_child
    FROM journal_entries je
    WHERE je.description LIKE '%2025年4月 社会保険料%'
    ORDER BY je.journal_entry_id
""")

rows = cur.fetchall()
for r in rows:
    print(f"ID:{r['journal_entry_id']:3d} 親:{r['parent_entry_id'] or '-':>3} 子:{r['has_child']} 削除:{r['is_deleted']} {r['description']}")

# 試算表と同じロジックで集計
print("\n=== 試算表と同じロジックでの集計（2025-06-01～2025-06-30） ===")
cur.execute("""
    SELECT 
        je.journal_entry_id,
        je.entry_date,
        je.description,
        jl.debit,
        jl.credit,
        je.parent_entry_id,
        je.is_deleted,
        CASE 
            WHEN EXISTS (SELECT 1 FROM journal_entries child WHERE child.parent_entry_id = je.journal_entry_id)
            THEN 'Y' ELSE 'N'
        END as has_child
    FROM journal_entries je
    JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
    JOIN accounts a ON jl.account_id = a.account_id
    WHERE a.account_code = '102'
    AND je.entry_date BETWEEN '2025-06-01' AND '2025-06-30'
    AND je.description <> '前期残高'
    AND je.is_deleted = false
    ORDER BY je.journal_entry_id
""")

print(f"\n{'ID':>3} {'日付':10} {'借方':>12} {'貸方':>12} {'親':>3} {'子':2} {'集計':4} 摘要")
print("-" * 120)

total_debit_all = 0
total_credit_all = 0
total_debit_filtered = 0
total_credit_filtered = 0

rows = cur.fetchall()
for r in rows:
    total_debit_all += r['debit']
    total_credit_all += r['credit']
    
    # 試算表のロジック: 子を持たない仕訳のみ集計
    should_include = r['has_child'] == 'N'
    
    if should_include:
        total_debit_filtered += r['debit']
        total_credit_filtered += r['credit']
    
    status = "集計" if should_include else "除外"
    parent_str = str(r['parent_entry_id']) if r['parent_entry_id'] else "-"
    
    print(f"{r['journal_entry_id']:3d} {r['entry_date']} {r['debit']:>12,.0f} {r['credit']:>12,.0f} {parent_str:>3} {r['has_child']:2} {status:4} {r['description'][:60]}")

print("-" * 120)
print(f"全仕訳:     借方={total_debit_all:>12,.0f} 貸方={total_credit_all:>12,.0f}")
print(f"試算表集計: 借方={total_debit_filtered:>12,.0f} 貸方={total_credit_filtered:>12,.0f}")

cur.close()
conn.close()
