from pathlib import Path


def path_to_module_name(path: Path, base_dir: Path | None = None) -> str:
    """Convert a Python file path to a dotted module name for tools and agents.

    This helper is used anywhere we need a stable module identifier for dynamically
    loaded code (e.g. CLI-loaded agents, tools discovered from the filesystem).

    Behaviour:
    - Strips the `.py` suffix from the path.
    - If the file is under the given ``base_dir`` (or current working directory
      when ``base_dir`` is None), it converts the relative path into a dotted
      module name, using each directory component as a segment.
    - If the file is not under ``base_dir``, it falls back to the filename stem.

    Examples:
    - path: /repo/demos/agents/basic_chatbot.py, base_dir=/repo
      -> "demos.agents.basic_chatbot"
    - path: /tmp/basic_chatbot.py, base_dir=/repo
      -> "basic_chatbot"
    """
    path = Path(path)
    # Remove extension
    path_no_ext = path.with_suffix("")

    if base_dir is None:
        base_dir = Path.cwd()
    else:
        base_dir = Path(base_dir)

    try:
        rel_path = path_no_ext.relative_to(base_dir)
    except ValueError:
        # Path is not within base_dir; fall back to simple stem
        return path_no_ext.stem

    return ".".join(rel_path.parts)
