import psycopg2

conn = psycopg2.connect(
    host="192.168.0.61",
    port=55432,
    database="njts_acct",
    user="njts_app",
    password="njts_app2025"
)

cur = conn.cursor()

print("=" * 140)
print("【試算表 - 資産科目の全体構成】")
print("=" * 140)

# 查询所有未删除的latest仕訳，计算每个科目的余额
cur.execute("""
    SELECT 
        a.account_id,
        a.account_code,
        a.account_name,
        a.account_type,
        COALESCE(SUM(jl.debit), 0) as total_debit,
        COALESCE(SUM(jl.credit), 0) as total_credit,
        COALESCE(SUM(jl.debit), 0) - COALESCE(SUM(jl.credit), 0) as balance
    FROM accounts a
    LEFT JOIN journal_lines jl ON a.account_id = jl.account_id
    LEFT JOIN journal_entries je ON jl.journal_entry_id = je.journal_entry_id 
        AND je.is_deleted = false 
        AND je.is_latest = true
    WHERE a.account_type IN ('資産', 'Asset', '流動資産', '非流動資産')
    GROUP BY a.account_id, a.account_code, a.account_name, a.account_type
    ORDER BY a.account_code
""")

accounts = cur.fetchall()

print("\n【個別科目の残高】\n")

total_assets = 0

for account_id, code, name, acc_type, debit, credit, balance in accounts:
    if balance != 0:
        print(f"{code:>4} | {name:20} | {acc_type:10} | 借={debit:>12,.0f}  貸={credit:>12,.0f} | 残高={balance:>12,.0f}円")
        total_assets += balance

print("\n" + "=" * 140)
print(f"【合計】資産合計: {total_assets:>15,.0f}円")
print("=" * 140)

# 再算一下普通預金的构成比
cur.execute("""
    SELECT 
        COALESCE(SUM(COALESCE(jl.debit, 0) - COALESCE(jl.credit, 0)), 0)
    FROM journal_lines jl
    INNER JOIN journal_entries je ON jl.journal_entry_id = je.journal_entry_id
    WHERE jl.account_id = 2  -- 普通預金
    AND je.is_deleted = false
    AND je.is_latest = true
""")

bank_balance = cur.fetchone()[0]

if total_assets > 0:
    ratio = (bank_balance / total_assets) * 100
    print(f"\n普通預金: {bank_balance:>15,.0f}円")
    print(f"資産合計: {total_assets:>15,.0f}円")
    print(f"構成比: {ratio:>15.2f}%")
    
    print(f"\n税理士の構成比: 31.39%")
    print(f"あなたの構成比: {ratio:.2f}%")
    
    if ratio > 40:
        print(f"\n⚠️  差異が大きい（税理士より{ratio - 31.39:.2f}ポイント高い）")
        print("原因の可能性：")
        print("  1. 他の資産科目（有形資産、投資資産など）の入力漏れ")
        print("  2. 負債科目（應収/應払）の入力不足")
        print("  3. データベースに含まれていない科目がある")
    else:
        print(f"\n✓ 比較的近い")
else:
    print("\n⚠️  資産残高がゼロです")

cur.close()
conn.close()
