from csirtmu.self_service_backend import input_structs, models


class StepBuilder:
    def build(
        self,
        data: list[
            input_structs.TextStepInput
            | input_structs.LinkStepInput
            | input_structs.FormStepInput
            | input_structs.NetboxSearchStepInput
            | input_structs.OutlineSearchStepInput
        ],
    ) -> list[models.TextStep | models.LinkStep | models.FormStep | models.NetboxSearchStep | models.OutlineSearchStep]:
        _check_prev_chains(data)
        return [step_data.to_model() for step_data in data]


def _check_prev_chains(
    data: list[
        input_structs.TextStepInput
        | input_structs.LinkStepInput
        | input_structs.FormStepInput
        | input_structs.NetboxSearchStepInput
        | input_structs.OutlineSearchStepInput
    ],
) -> None:
    error_msg = "Malformed config: "
    if len([step for step in data if step.prev_id is None]) != 1:
        error_msg += "No single start step"
        raise ValueError(error_msg)
    for step in data:
        if (
            step.prev_id is not None
            and len([step2 for step2 in data if step2.id == step.prev_id and step2.id != step.id]) != 1
        ):
            error_msg += "Prev step is missing"
            raise ValueError(error_msg)
