"""Agent CLI run pipe command - execute a pipeline by pipe code."""

from __future__ import annotations

import asyncio
import functools
from pathlib import Path
from typing import Annotated, Any

import typer
from mthds.runners.types import RunnerType

from pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_cli
from pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat, agent_error, agent_success_formatted, set_agent_cli_error_format
from pipelex.cli.agent_cli.commands.run._output_helpers import format_run_markdown
from pipelex.cli.agent_cli.commands.run._run_core import run_pipeline_core
from pipelex.cli.agent_cli.commands.run._run_core_api import run_pipeline_core_api
from pipelex.cli.agent_cli.commands.run.stdin_resolver import parse_cli_inputs
from pipelex.cli.method_resolver import resolve_pipe_from_exports
from pipelex.core.interpreter.helpers import MTHDS_EXTENSION, is_pipelex_file
from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError
from pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError
from pipelex.pipelex import Pipelex
from pipelex.pipeline.exceptions import PipelineExecutionError


def run_pipe_cmd(
    ctx: typer.Context,
    pipe_code: Annotated[
        str,
        typer.Argument(help="Pipe code to run"),
    ],
    inputs: Annotated[
        str | None,
        typer.Option("--inputs", "-i", help="Path to JSON file with inputs or inline JSON"),
    ] = None,
    dry_run: Annotated[
        bool,
        typer.Option("--dry-run", help="Run pipeline in dry mode (no actual inference calls)"),
    ] = False,
    mock_inputs: Annotated[
        bool,
        typer.Option("--mock-inputs", help="Generate mock data for missing required inputs (requires --dry-run)"),
    ] = False,
    graph: Annotated[
        bool,
        typer.Option("--graph/--no-graph", help="Generate execution graph visualizations (saved alongside output)"),
    ] = True,
    library_dir: Annotated[
        list[str] | None,
        typer.Option("--library-dir", "-L", help="Directory to search for pipe definitions (.mthds files)"),
    ] = None,
    with_memory: Annotated[
        bool,
        typer.Option("--with-memory", help="Include full working memory in output (for piping to another method)"),
    ] = False,
    output_format: Annotated[
        CliOutputFormat,
        typer.Option("--format", help="Success output format: markdown (default) or json (structured)"),
    ] = CliOutputFormat.MARKDOWN,
    error_format: Annotated[
        CliOutputFormat | None,
        typer.Option("--error-format", help="Error output format (defaults to --format value): markdown or json"),
    ] = None,
) -> None:
    """Execute a pipeline by pipe code and output the results.

    Default output is markdown; use --format json for structured JSON.
    Results go to stdout on success, errors to stderr with exit code 1.
    Graph visualizations are generated by default; use --no-graph to disable.

    Examples:
        pipelex-agent run pipe my_pipe
        pipelex-agent run pipe my_pipe --inputs data.json
        pipelex-agent run pipe my_pipe --dry-run --mock-inputs
        pipelex-agent run pipe my_pipe --format json
    """
    set_agent_cli_error_format(error_format or output_format)

    # Helpful error if the user passes a path instead of a pipe code
    target_path = Path(pipe_code)
    if target_path.is_dir() or is_pipelex_file(target_path) or pipe_code.endswith(MTHDS_EXTENSION):
        agent_error(
            f"'{pipe_code}' looks like a file path or directory. "
            f"Use 'run bundle {pipe_code}' for bundles/directories, or 'run pipe <code>' for pipe codes.",
            "ArgumentError",
        )

    # Validate --mock-inputs requires --dry-run
    if mock_inputs and not dry_run:
        agent_error("--mock-inputs requires --dry-run", "ArgumentError")

    # Check installed methods' exports for additional library dirs
    try:
        export_dirs = resolve_pipe_from_exports(pipe_code)
    except ValueError as exc:
        agent_error(
            f"Ambiguous pipe code '{pipe_code}': {exc}",
            "ArgumentError",
            cause=exc,
        )
    if export_dirs:
        if library_dir is None:
            library_dir = export_dirs
        else:
            library_dir = [*export_dirs, *library_dir]

    # Load inputs: --inputs flag takes priority, then stdin fallback
    pipeline_inputs: dict[str, Any] | None = parse_cli_inputs(inputs_arg=inputs, stdin_fallback=True)

    runner_type: RunnerType = ctx.obj["runner"]

    match runner_type:
        case RunnerType.API:
            # Validate unsupported flags for API runner
            if dry_run:
                agent_error("--dry-run is not supported with --runner api", "ArgumentError")
            if mock_inputs:
                agent_error("--mock-inputs is not supported with --runner api", "ArgumentError")

            from mthds.client.exceptions import ClientAuthenticationError, PipelineRequestError  # noqa: PLC0415

            try:
                result = asyncio.run(
                    run_pipeline_core_api(
                        pipe_code=pipe_code,
                        inputs=pipeline_inputs,
                        with_memory=with_memory,
                    )
                )
                agent_success_formatted(result, functools.partial(format_run_markdown, with_memory=with_memory), output_format)

            except ClientAuthenticationError as exc:
                agent_error(str(exc), "ClientAuthenticationError", cause=exc)

            except PipelineRequestError as exc:
                agent_error(str(exc), "PipelineRequestError", cause=exc)

            except Exception as exc:  # noqa: BLE001
                # Agent CLI command boundary: agent_error() (NoReturn) converts any unexpected failure into the structured error payload.
                agent_error(str(exc), type(exc).__name__, cause=exc)

        case RunnerType.PIPELEX:
            make_pipelex_for_agent_cli(log_level=ctx.obj["log_level"], needs_inference=not dry_run, needs_model_specs=True)

            try:
                result = asyncio.run(
                    run_pipeline_core(
                        pipe_code=pipe_code,
                        inputs=pipeline_inputs,
                        dry_run=dry_run,
                        mock_inputs=mock_inputs,
                        library_dirs=library_dir,
                        graph=graph,
                        with_memory=with_memory,
                    )
                )
                agent_success_formatted(result, functools.partial(format_run_markdown, with_memory=with_memory), output_format)

            except PipelineExecutionError as exc:
                extra_fields: dict[str, Any] = {
                    "pipe_code": exc.pipe_code,
                    "pipe_stack": exc.pipe_stack,
                }
                if exc.__cause__:
                    extra_fields["cause_type"] = type(exc.__cause__).__name__
                    extra_fields["cause_message"] = str(exc.__cause__)
                agent_error(exc.message, "PipelineExecutionError", cause=exc, **extra_fields)

            except PipeOperatorModelChoiceError as exc:
                agent_error(
                    exc.message,
                    "PipeOperatorModelChoiceError",
                    cause=exc,
                    pipe_code=exc.pipe_code,
                    model_type=str(exc.model_type),
                    model_choice=str(exc.model_choice),
                )

            except PipeOperatorModelAvailabilityError as exc:
                availability_extra: dict[str, Any] = {
                    "pipe_code": exc.pipe_code,
                    "model_handle": exc.model_handle,
                }
                if exc.fallback_list:
                    availability_extra["fallback_list"] = exc.fallback_list
                if exc.pipe_stack:
                    availability_extra["pipe_stack"] = exc.pipe_stack
                agent_error(exc.message, "PipeOperatorModelAvailabilityError", cause=exc, **availability_extra)

            except Exception as exc:  # noqa: BLE001
                # Agent CLI command boundary: agent_error() (NoReturn) converts any unexpected failure into the structured error payload.
                agent_error(str(exc), type(exc).__name__, cause=exc)

            finally:
                Pipelex.teardown_if_needed()
