"""Flow-control nodes — ConditionalNode.

- ConditionalNode: routes to different targets based on a condition expression
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Literal

from core.pathways.expressions import safe_eval
from core.pathways.models.io import NodeInputs, NodeOutputs
from core.pathways.nodes.base import NodeBase
from core.pathways.nodes.models import ConditionalOutput

if TYPE_CHECKING:
    from core.pathways.context import Context


class ConditionalNode(NodeBase):
    """Conditional branching node — routes to different targets based on a condition.

    Evaluates the condition expression and returns which branch to take.
    The pathway VM uses the result to determine the next node.

    Attributes
    ----------
    condition : str
        Expression to evaluate (e.g. ``"{{review.approved}} == true"``).
    true_node : str
        Node ID to go to if condition is true.
    false_node : str
        Node ID to go to if condition is false.
    """

    type: Literal["conditional"] = "conditional"
    condition: str
    true_node: str
    false_node: str

    async def compute(self, inputs: NodeInputs, _ctx: Context) -> NodeOutputs:
        """Evaluate condition and return branch decision."""
        template_data = inputs.to_dict()
        formatted = self._format_template(self.condition, template_data)
        branch = bool(safe_eval(formatted, env=template_data))

        target = self.true_node if branch else self.false_node
        output = ConditionalOutput(
            branch="true" if branch else "false",
            next_node=target,
            selected_route=target,
            condition_result=branch,
        )
        return NodeOutputs(output=output.model_dump(), selected_route=target)


__all__ = [
    "ConditionalNode",
]
