"""Pipeline create command implementation."""

from pathlib import Path
from typing import Optional

import typer

from cli.commands.pipelines.create.presenter import present_pipeline_create_success
from cli.infrastructure.command import async_command, authenticated_client
from alloy_runtime_types.dtos.pipeline import CreatePipelineRequest


def pipelines_create_command(
    name: str = typer.Option(
        ...,
        "--name",
        "-n",
        help="Pipeline name",
    ),
    description: Optional[str] = typer.Option(
        None,
        "--description",
        "-d",
        help="Pipeline description",
    ),
    file: Path = typer.Option(
        ...,
        "--file",
        "-f",
        help="Python file containing @pipeline decorated function",
        exists=True,
        readable=True,
    ),
    function_name: Optional[str] = typer.Option(
        None,
        "--function-name",
        help="Name of the @pipeline function to run (uses first/only if not specified)",
    ),
    public: bool = typer.Option(
        False,
        "--public/--no-public",
        help="Make pipeline publicly accessible",
    ),
) -> None:
    """Create a new pipeline from a Python file.

    The file must contain a @pipeline decorated function.

    Examples:
        alloy pipelines create --name my-pipeline --file pipeline.py
        alloy pipelines create -n my-pipeline -f pipeline.py --public
        alloy pipelines create -n my-pipeline -f pipeline.py --function-name main_pipeline
    """
    _validate_file_extension(file)
    _execute_create(
        name=name,
        description=description,
        file=file,
        function_name=function_name,
        public=public,
    )


def _validate_file_extension(file: Path) -> None:
    """Validate file has .py extension."""
    if file.suffix != ".py":
        raise typer.BadParameter(
            f"File must have .py extension, got: {file.suffix}",
            param_hint="--file",
        )


def _execute_create(
    name: str,
    description: Optional[str],
    file: Path,
    function_name: Optional[str],
    public: bool,
) -> None:
    """Build and execute pipeline creation from command flags."""
    module_content = file.read_text()

    if not module_content.strip():
        raise typer.BadParameter("Pipeline file cannot be empty", param_hint="--file")

    request = CreatePipelineRequest(
        name=name,
        description=description,
        module_content=module_content,
        pipeline_function_name=function_name,
        is_public=public,
    )

    _create_pipeline(request)


@async_command
async def _create_pipeline(request: CreatePipelineRequest) -> None:
    """Create pipeline via API."""
    async with authenticated_client() as (_config, client):
        response = await client.create_pipeline(request)

    present_pipeline_create_success(response)
