"""Render a row workflow configuration from a workflow spec."""

from __future__ import annotations

from pathlib import Path
from typing import Optional

from .spec import WorkflowSpec


def render_row_workflow(
    spec: WorkflowSpec,
    output_path: str | Path,
    default_command: Optional[str] = None,
) -> Path:
    """Render a row workflow TOML file for the provided spec.

    Parameters
    ----------
    spec
        Validated workflow specification.
    output_path
        Where to write the workflow TOML.
    default_command
        Optional format string used when an action does not define ``runner``.
        Defaults to ``python actions/{name}.py {directory}``.
    """

    default_command = default_command or "python actions/{name}.py {directory}"
    out_path = Path(output_path)

    lines = [
        "# Generated by grubicy",
        "[workspace]",
        f'value_file = "{spec.workspace.value_file}"',
        "",
    ]

    for action in spec.actions:
        command = action.runner or default_command.format(
            name=action.name, directory="{directory}"
        )
        lines.append("[[action]]")
        lines.append(f'name = "{action.name}"')
        lines.append(f'command = "{command}"')
        if action.outputs:
            outputs_str = ", ".join(f'"{p}"' for p in action.outputs)
            lines.append(f"products = [{outputs_str}]")
        lines.append("[[action.group.include]]")
        lines.append(f'condition = ["/action", "==", "{action.name}"]')
        lines.append("")

    out_path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
    return out_path
