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("=" * 160)
print("【試算表 - 全科目の構成（account_type別）】")
print("=" * 160)

# 查询所有科目的余额
cur.execute("""
    SELECT 
        a.account_id,
        a.account_code,
        a.account_name,
        a.account_type,
        COALESCE(SUM(jl.debit), 0)::BIGINT as total_debit,
        COALESCE(SUM(jl.credit), 0)::BIGINT 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
    GROUP BY a.account_id, a.account_code, a.account_name, a.account_type
    ORDER BY a.account_type, a.account_code
""")

accounts = cur.fetchall()

print("\n")

current_type = None
type_total = {}

for account_id, code, name, acc_type, debit, credit, balance in accounts:
    if balance != 0:
        if current_type != acc_type:
            if current_type is not None:
                subtotal = type_total.get(current_type, 0)
                print(f"  └─ 小計（{current_type}）: {subtotal:>15,.0f}円\n")
            current_type = acc_type
            print(f"【{acc_type.upper()}】")
        
        print(f"  {code:>4} | {name:30} | 借={debit:>12,.0f}  貸={credit:>12,.0f} | 残高={balance:>12,.0f}円")
        
        if acc_type not in type_total:
            type_total[acc_type] = 0
        type_total[acc_type] += balance

# 最後の小計
if current_type is not None:
    subtotal = type_total.get(current_type, 0)
    print(f"  └─ 小計（{current_type}）: {subtotal:>15,.0f}円\n")

print("=" * 160)
print("【科目別合計】")
print("=" * 160)

total_balance = 0
for acc_type in ['asset', 'liability', 'equity', 'revenue', 'expense']:
    if acc_type in type_total:
        balance = type_total[acc_type]
        print(f"{acc_type:12}: {balance:>15,.0f}円")
        total_balance += balance

print(f"\n{'合計':12}: {total_balance:>15,.0f}円")

# 计算普通預金的构成比
if total_balance != 0 and 'asset' in type_total:
    asset_total = type_total['asset']
    
    # 查询普通預金的具体值
    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  -- 普通預金(code=102)
        AND je.is_deleted = false
        AND je.is_latest = true
    """)
    
    bank_balance = cur.fetchone()[0]
    
    print("\n" + "=" * 160)
    print("【構成比】")
    print("=" * 160)
    print(f"\n普通預金: {bank_balance:>15,.0f}円")
    print(f"資産合計: {asset_total:>15,.0f}円")
    
    if asset_total > 0:
        ratio = (bank_balance / asset_total) * 100
        print(f"構成比（資産内）: {ratio:>12.2f}%")
    
    if total_balance > 0:
        ratio_total = (bank_balance / total_balance) * 100
        print(f"構成比（全体）: {ratio_total:>15.2f}%")
    
    print(f"\n税理士の構成比: 31.39%")
    if total_balance > 0:
        ratio_total = (bank_balance / total_balance) * 100
        print(f"あなたの構成比: {ratio_total:.2f}%")
        diff = ratio_total - 31.39
        if abs(diff) > 5:
            print(f"\n⚠️  差異: {diff:+.2f}ポイント（{abs(diff):.2f}ポイント）")
            if diff > 0:
                print("  → あなたの方が普通預金の比率が高い（他の資産が少ない可能性）")
            else:
                print("  → 税理士の方が普通預金の比率が高い（あなたが入力していない資産がある可能性）")

cur.close()
conn.close()
