from __future__ import annotations

import os
import tempfile
from typing import Callable


def _mkdtemp_compat(
    suffix: str | None = None,
    prefix: str | None = None,
    dir: str | None = None,
) -> str:
    # Python 3.14 on some Windows hosts creates mkdtemp dirs that are
    # immediately non-writable by the same process when mode=0o700 is used.
    # pip relies heavily on tempfile; force 0o777 for compatibility.
    if dir is None:
        dir = tempfile.gettempdir()
    if prefix is None:
        prefix = tempfile.template
    if suffix is None:
        suffix = ""

    names = tempfile._get_candidate_names()
    for _ in range(tempfile.TMP_MAX):
        name = next(names)
        path = os.path.join(dir, f"{prefix}{name}{suffix}")
        try:
            os.mkdir(path, 0o777)
            return path
        except FileExistsError:
            continue

    raise FileExistsError("No usable temporary directory name found.")


def main(argv: list[str]) -> int:
    tempfile.mkdtemp = _mkdtemp_compat  # type: ignore[assignment]

    from pip._internal.cli.main import main as pip_main

    return int(pip_main(argv))


if __name__ == "__main__":
    raise SystemExit(main(__import__("sys").argv[1:]))

