from __future__ import annotations

from app.modules.agent.engine.orchestrator.models import ExecutionPlan, PlanStatus, TaskSpec


class PlanCompiler:
    def compile(self, template: ExecutionPlan, task: TaskSpec) -> ExecutionPlan:
        plan = template.model_copy(deep=True)
        plan.plan_id = f"{task.task_id}:{template.template_id}"
        plan.task_id = task.task_id
        plan.status = PlanStatus.DRAFT
        plan.variables = {
            "scenario": task.scenario.value,
            "route": {
                "domain_id": task.routing.domain_id,
                "process_id": task.routing.process_id,
                "confidence": task.routing.confidence,
            },
        }

        for step in plan.steps:
            step.timeout_sec = max(1, min(step.timeout_sec, task.constraints.step_timeout_sec))
            step.retry.max_attempts = max(1, min(step.retry.max_attempts, task.constraints.max_retries_per_step))
            if step.side_effect == "write" and not task.constraints.allow_writes:
                step.on_failure = "fail"

        if len(plan.steps) > task.constraints.max_steps:
            plan.steps = plan.steps[: task.constraints.max_steps]

        return plan
