"""Automatically activate, and deactivate virutal environments."""

import itertools
import os
import pathlib

VENVER_FILE = ".venver"


def auto() -> str:
    """Return the command to activate, or deactivate a virutal environment.

    The path to the environment to activate must be the first line of a
    ``.venver`` file. The command to activate the environment in this file will
    be returned whenever entering the directory containing this file, or any
    descendant directory.

    The command to deactivate the environment will be returned whenever
    navigating outside of the ``.venver`` directory.

    If the environment is manually deactivated, an activate command will not be
    returned, unless you navigate outside the ``.venver`` directory, then
    reenter it.

    Usually, the environment is located in the same directory as the
    ``.venver`` file. However, you may specify an environment path outside of
    the ``.venver`` directory. In this case commands will still be returned
    based on navigation relative to the ``.venver`` directory, and not the
    environment directory.
    """
    venver_root = os.getenv("VENVER_ROOT")
    cwd = pathlib.Path.cwd()

    if venver_root:
        if not cwd.is_relative_to(pathlib.Path(venver_root)):
            return "unset VENVER_ROOT;command -v deactivate 1 > /dev/null && deactivate"
        return ""

    for cur in itertools.chain((cwd,), cwd.parents):  # pragma: no cover  # TODO @NAS: write tests
        maybe_venver = cur / VENVER_FILE
        if maybe_venver.exists():
            with maybe_venver.open() as f:
                maybe_venv_activate = pathlib.Path(f.readline().strip()) / "bin" / "activate"
                if maybe_venv_activate.exists():
                    return f"export VENVER_ROOT='{cur}';source {maybe_venv_activate}"

    return ""


def cli() -> int:  # pragma: no cover
    """The command-line interface."""
    print(auto())  # noqa: T201
    return 0
