from __future__ import annotations

import argparse
from collections.abc import Callable
from types import ModuleType


def parse_args(
    *,
    description: str,
    argv: list[str] | None,
    configure: Callable[[argparse.ArgumentParser], None],
) -> argparse.Namespace:
    """Build a parser, register arguments, and parse argv."""
    parser = argparse.ArgumentParser(description=description)
    configure(parser)
    return parser.parse_args(argv)


def missing_optional_deps_message(
    *,
    extras: str,
    run_as_module: str,
    run_tail: str = "",
) -> str:
    suffix = f" {run_tail}" if run_tail else ""
    extra_names = [
        token
        for idx, token in enumerate(extras.split())
        if idx > 0 and extras.split()[idx - 1] == "--extra"
    ]
    extras_csv = ",".join(extra_names)
    package_spec = f"ketju[{extras_csv}]" if extras_csv else "ketju"
    return (
        "Missing optional dependencies for this example.\n"
        "If you are in this repository, install with:\n"
        f"  uv sync {extras}\n"
        "Or install all example extras:\n"
        "  uv sync --extra examples\n"
        "\n"
        "If you are using ketju outside this repository, install with:\n"
        f"  uv add \"{package_spec}\"\n"
        "Or:\n"
        f"  uv pip install \"{package_spec}\"\n"
        "\n"
        "Then run:\n"
        f"  uv run python -m {run_as_module}{suffix}"
    )


def import_agent_module() -> ModuleType:
    """Import the pydantic-ai agent module for module/script execution styles."""
    try:
        # Works when executed as module: `python -m ketju.examples.<name>`.
        from ..agents.pydantic_ai import agent as agent_module  # type: ignore
    except ImportError:
        # Works when executed as script path: `python src/ketju/examples/<name>.py`.
        from ketju.agents.pydantic_ai import agent as agent_module  # type: ignore
    return agent_module
