"""财务管理 — 账号注册/充值/预算"""

from __future__ import annotations

import json
import logging
from pathlib import Path

from tool_agent.config import settings

logger = logging.getLogger(__name__)


class FinanceManager:
    """管理 API 账号和预算"""

    def __init__(self) -> None:
        self.billing_path = settings.data_dir / "billing_log.json"

    def check_budget(self, amount_usd: float) -> bool:
        """检查是否在预算内"""
        return amount_usd <= settings.single_tx_limit_usd

    def needs_approval(self, amount_usd: float) -> bool:
        """是否需要人工审批"""
        return amount_usd > settings.require_approval_above_usd

    def record_transaction(self, provider: str, amount_usd: float, description: str) -> None:
        """记录支出"""
        log = json.loads(self.billing_path.read_text()) if self.billing_path.exists() else {"transactions": []}
        log["transactions"].append({
            "provider": provider,
            "amount_usd": amount_usd,
            "description": description,
        })
        self.billing_path.write_text(json.dumps(log, indent=2, ensure_ascii=False))
        logger.info(f"Recorded transaction: {provider} ${amount_usd}")
