"""Discover the Obsidian vaults that live directly under a base directory."""

import os


def list_obsidian_vaults(base_dir: str) -> list:
    """Return the Obsidian vaults found one level below ``base_dir``.

    A directory is considered an Obsidian vault when it contains an
    ``.obsidian/`` subdirectory (the folder Obsidian creates to hold its
    per-vault configuration). Only the immediate children of ``base_dir`` are
    inspected; the search is not recursive, so nested vaults inside a vault are
    not reported.

    Impure: it reads the filesystem. Raises ``FileNotFoundError`` if
    ``base_dir`` does not exist and ``NotADirectoryError`` if it is not a
    directory.

    Args:
        base_dir: Directory that holds Obsidian vaults as subfolders, e.g.
            ``/home/enmanuel/Obsidian``.

    Returns:
        A list of dicts ``{"name": str, "path": str}`` (one per vault), sorted
        by name. ``path`` is the absolute path of the vault directory.
    """
    base = os.path.abspath(base_dir)
    if not os.path.exists(base):
        raise FileNotFoundError(f"base directory does not exist: {base}")
    if not os.path.isdir(base):
        raise NotADirectoryError(f"base path is not a directory: {base}")

    vaults: list[dict] = []
    for entry in os.scandir(base):
        if not entry.is_dir():
            continue
        if os.path.isdir(os.path.join(entry.path, ".obsidian")):
            vaults.append({"name": entry.name, "path": os.path.abspath(entry.path)})

    vaults.sort(key=lambda v: v["name"])
    return vaults


if __name__ == "__main__":
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        # Two real vaults, one plain dir, one file.
        os.makedirs(os.path.join(tmp, "VaultA", ".obsidian"))
        os.makedirs(os.path.join(tmp, "VaultB", ".obsidian"))
        os.makedirs(os.path.join(tmp, "NotAVault"))
        with open(os.path.join(tmp, "loose.md"), "w") as f:
            f.write("not a dir")

        vaults = list_obsidian_vaults(tmp)
        names = [v["name"] for v in vaults]
        assert names == ["VaultA", "VaultB"], names
        assert all(os.path.isabs(v["path"]) for v in vaults), vaults

    print("OK")
