"""
税理士の残高試算表とシステムのデータを比較するスクリプト
期間: 2025年6月1日〜2025年12月31日
"""
import psycopg2

conn = psycopg2.connect(
    host='192.168.0.61',
    port=55432,
    dbname='njts_acct',
    user='njts_app',
    password='njts_app2025'
)
cur = conn.cursor()

print("=" * 80)
print("【システム】損益計算書 (2025年6月1日〜2025年12月31日)")
print("=" * 80)

# Get P&L accounts breakdown (account_type: 収益・費用 etc.)
query = """
SELECT 
    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,
    CASE 
        WHEN a.account_type IN ('revenue', '収益', 'income') 
            THEN COALESCE(SUM(jl.credit), 0) - COALESCE(SUM(jl.debit), 0)
        ELSE 
            COALESCE(SUM(jl.debit), 0) - COALESCE(SUM(jl.credit), 0)
    END 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_latest = true
    AND je.is_deleted = false
    AND je.entry_date >= '2025-06-01'
    AND je.entry_date <= '2025-12-31'
WHERE a.account_type NOT IN ('asset', 'liability', 'equity', '資産', '負債', '純資産', '資本')
GROUP BY a.account_id, a.account_code, a.account_name, a.account_type
HAVING COALESCE(SUM(jl.debit), 0) + COALESCE(SUM(jl.credit), 0) != 0
ORDER BY a.account_code
"""

cur.execute(query)
rows = cur.fetchall()

if rows:
    print(f"{'科目コード':<10} {'科目名':<20} {'種別':<15} {'借方合計':>12} {'貸方合計':>12} {'残高':>12}")
    print("-" * 85)
    for row in rows:
        print(f"{str(row[0]):<10} {str(row[1]):<20} {str(row[2]):<15} {row[3]:>12,.0f} {row[4]:>12,.0f} {row[5]:>12,.0f}")
else:
    print("データが見つかりません。account_typeを確認します...")
    cur.execute("SELECT DISTINCT account_type FROM accounts ORDER BY account_type")
    types = cur.fetchall()
    print("account_typeの一覧:", [t[0] for t in types])

print()
print("=" * 80)
print("【システム】勘定科目別集計（全科目）")
print("=" * 80)

query2 = """
SELECT 
    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
FROM accounts a
JOIN journal_lines jl ON a.account_id = jl.account_id
JOIN journal_entries je ON jl.journal_entry_id = je.journal_entry_id
WHERE je.is_latest = true
    AND je.is_deleted = false
    AND je.entry_date >= '2025-06-01'
    AND je.entry_date <= '2025-12-31'
GROUP BY a.account_id, a.account_code, a.account_name, a.account_type
ORDER BY a.account_code
"""

cur.execute(query2)
rows2 = cur.fetchall()

if rows2:
    print(f"{'科目コード':<10} {'科目名':<25} {'種別':<15} {'期間借方':>12} {'期間貸方':>12}")
    print("-" * 80)
    for row in rows2:
        print(f"{str(row[0]):<10} {str(row[1]):<25} {str(row[2]):<15} {row[3]:>12,.0f} {row[4]:>12,.0f}")

print()
print("=" * 80)
print("【比較】税理士試算表との差異分析")
print("=" * 80)

# Tax accountant figures from PDF
accountant_figures = {
    "売上高": 28896368,
    "役員報酬": 2520000,
    "給料手当": 2700000,
    "賞与": 4300000,
    "法定福利費": 1588604,
    "福利厚生費": 242978,
    "外注費": 7490000,
    "交際費": 915007,
    "会議費": 219070,
    "旅費交通費": 522149,
    "通信費": 31459,
    "消耗品費": 1027007,
    "修繕費": 986,
    "新聞図書費": 9900,
    "支払手数料": 168800,
    "地代家賃": 1081822,
    "保険料": 33950,
    "租税公課": 33100,
    "受取利息": 4878,
    "法人税住民税事業税": 747,
}

print("\n税理士試算表の数値:")
total_revenue = 0
total_expense = 0
for k, v in accountant_figures.items():
    if k in ["売上高", "受取利息"]:
        total_revenue += v
        print(f"  {k:<20}: {v:>12,.0f} (収益)")
    else:
        total_expense += v
        print(f"  {k:<20}: {v:>12,.0f} (費用)")

print(f"\n  収益合計   : {total_revenue:>12,.0f}")
print(f"  費用合計   : {total_expense:>12,.0f}")
print(f"  当期純損益  : {total_revenue - total_expense:>12,.0f}")
print(f"\n  税理士の当期純損益: 6,015,667")
print(f"  自社の当期純損益  : 9,461,950")
print(f"  差 額              : {9461950 - 6015667:>12,.0f}")

conn.close()
