"""
Utilities for pip configuration.
"""

from __future__ import annotations

import os
import sys
from pathlib import Path
from typing import TYPE_CHECKING

import platformdirs

if TYPE_CHECKING:
    from collections.abc import Mapping


PIP_CONFIG_FILE_ENV_VAR = "PIP_CONFIG_FILE"
VIRTUAL_ENV_ENV_VAR = "VIRTUAL_ENV"
CONDA_PREFIX_ENV_VAR = "CONDA_PREFIX"
WINDOWS_PIP_CONFIG_FILENAME = "pip.ini"
UNIX_PIP_CONFIG_FILENAME = "pip.conf"


def pip_config_filename() -> str:
    """
    Return the pip configuration filename for the current platform.

    Returns
    -------
    str
        ``pip.ini`` on Windows, ``pip.conf`` elsewhere.

    """
    if sys.platform.startswith("win"):
        return WINDOWS_PIP_CONFIG_FILENAME
    return UNIX_PIP_CONFIG_FILENAME


def resolve_pip_config_path(*, env: Mapping[str, str] | None = None) -> Path:
    """
    Resolve the pip configuration file path.

    The resolution follows this priority order:

    1. ``PIP_CONFIG_FILE`` environment variable (explicit override).
    3. ``CONDA_PREFIX`` — path inside the active conda environment.
    2. ``VIRTUAL_ENV`` — path inside the active virtual environment.
    4. User-level config directory resolved by :mod:`platformdirs`.

    Parameters
    ----------
    env
        Environment variables mapping. Defaults to :data:`os.environ`.

    Returns
    -------
    Path
        The path to the pip configuration file.

    """
    environment: Mapping[str, str] = env if env is not None else os.environ
    filename = pip_config_filename()

    # Priority 1: explicit override
    if pip_config_file := environment.get(PIP_CONFIG_FILE_ENV_VAR):
        return Path(pip_config_file)

    # Priority 2: inside a conda environment
    if conda_prefix := environment.get(CONDA_PREFIX_ENV_VAR):
        return Path(conda_prefix) / filename

    # Priority 3: inside a virtual environment
    if virtual_env := environment.get(VIRTUAL_ENV_ENV_VAR):
        return Path(virtual_env) / filename

    # Priority 4: user-level config resolved by platformdirs
    return platformdirs.user_config_path("pip") / filename
