#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
import json

# 試算表API取得
api_url = "http://127.0.0.1:18080/trial-balance"
params = {
    "date_from": "2025-06-01",
    "date_to": "2025-12-31"
}

response = requests.get(api_url, params=params, timeout=10)
if response.status_code != 200:
    print("API Error:", response.text)
    exit(1)

data = response.json()

# 損益計算科目を全て抽出
pl_items = {}
for row in data.get('accounts', []):
    code = str(row.get('account_code', '')).strip()
    name = row.get('account_name', '')
    debit = float(row.get('debit', 0) or 0)
    credit = float(row.get('credit', 0) or 0)
    
    # 損益計算科目
    if code in ('701', '702', '709', '801', '802', '803', '804', '805', '806', '807', '808', '809', '810', '811', '812', '813', '814', '815', '816', '817', '818', '819', '820', '504', '505'):
        pl_items[code] = {
            'name': name,
            'debit': debit,
            'credit': credit
        }

# 全損益科目出力
print("=" * 80)
print("P/L Items Details")
print("=" * 80)
print(f"{'Code':<10} {'Name':<30} {'Debit':>15} {'Credit':>15}")
print("-" * 80)

total_operating_expenses = 0
for code in sorted(pl_items.keys()):
    item = pl_items[code]
    print(f"{code:<10} {item['name']:<30} {item['debit']:>15,.0f} {item['credit']:>15,.0f}")
    
    if code in ('802', '803', '804', '805', '806', '807', '808', '809', '810', '811', '812', '813', '814', '815', '816', '817', '818', '819', '820'):
        total_operating_expenses += item['debit'] - item['credit']

print("-" * 80)

# 計算
operating_revenue = pl_items.get('701', {}).get('credit', 0) - pl_items.get('701', {}).get('debit', 0)
cogs = pl_items.get('801', {}).get('debit', 0) - pl_items.get('801', {}).get('credit', 0)
non_op_702 = pl_items.get('702', {}).get('credit', 0) - pl_items.get('702', {}).get('debit', 0)
non_op_709 = pl_items.get('709', {}).get('credit', 0) - pl_items.get('709', {}).get('debit', 0)
non_operating_revenue = non_op_702 + non_op_709
corporate_tax = pl_items.get('504', {}).get('credit', 0) - pl_items.get('504', {}).get('debit', 0)
consumption_tax = pl_items.get('505', {}).get('credit', 0) - pl_items.get('505', {}).get('debit', 0)

gross_profit = operating_revenue - cogs
operating_profit = gross_profit - total_operating_expenses
ordinary_profit = operating_profit + non_operating_revenue
# 当期純利益（税引前）= 経常利益（504,505は負債科目のため含めない）
net_profit = ordinary_profit

print("\nCalculation Results:")
print(f"Operating Revenue (701): {operating_revenue:,.0f}")
print(f"COGS (801):              {cogs:,.0f}")
print(f"Gross Profit:            {gross_profit:,.0f}")
print(f"Operating Expenses:      {total_operating_expenses:,.0f}")
print(f"Operating Profit:        {operating_profit:,.0f}")
print(f"Non-op Revenue:          {non_operating_revenue:,.0f}")
print(f"Ordinary Profit:         {ordinary_profit:,.0f}")
print(f"NET PROFIT (Before Tax): {net_profit:,.0f}")

print(f"\nAccountant Data:         7193796")
print(f"Difference:              {net_profit - 7193796:,.0f}")
print(f"(Note: Our amount is PRE-TAX. Accountant data may include tax effects.)")
