from __future__ import annotations

from dataclasses import dataclass, field

from smartwallet.model.base import BudgetComponent


@dataclass
class Category(BudgetComponent):
    children: list[BudgetComponent] = field(default_factory=list)

    def add(self, component: BudgetComponent) -> None:
        self.children.append(component)

    def remove(self, component_id: str) -> None:
        self.children = [child for child in self.children if child.id != component_id]

    def get_balance(self) -> dict[str, float]:
        total_income = 0.0
        total_expense = 0.0

        for child in self.children:
            balance = child.get_balance()
            total_income += balance["income"]
            total_expense += balance["expense"]

        return {
            "income": round(total_income, 2),
            "expense": round(total_expense, 2),
            "total": round(total_income + total_expense, 2),
        }

    def to_dict(self) -> dict[str, object]:
        return {
            "type": "category",
            "id": self.id,
            "name": self.name,
            "created_at": self.created_at,
            "children": [child.to_dict() for child in self.children],
        }
