def _pip_install_upgrade_only_if_needed(reqs_to_install: list[ReqFileEntry], currently_installed: list[ReqFileEntry]):
    import tempfile
    import venv

    with tempfile.TemporaryDirectory() as tmp_venv_dir:
        out = venv.EnvBuilder(with_pip=True)
        out.create(tmp_venv_dir)
        context = out.ensure_directories(tmp_venv_dir)

        py_exe = context.env_exe

        output_upgrade_pip = pip_cli(["install", "--upgrade", "pip"], py_exe)

        # empty venv, install currently installed
        target_current = [r.name + "==" + r.version for r in currently_installed]
        target_current = ["pandas==1.4.0"]
        output_pip_current = pip_cli(["install"] + target_current, py_exe)

        target_upgrade = [r.name + "==" + r.version for r in reqs_to_install]
        cmd = [
            "install",
            "--upgrade-strategy",
            "only-if-needed",
            "--dry-run",
            "--report",
            "-",
            "--quiet",
        ] + target_upgrade
        output_pip_upgrade = pip_cli(cmd, py_exe)


# SPDX-FileCopyrightText: 2022-present Jeroen van Zundert <mail@jeroenvanzundert.nl>
#
# SPDX-License-Identifier: MIT

from __future__ import annotations

from pathlib import Path

from pipxl.__about__ import __version__
from pipxl.data import Environment, ReqFileEntry
from pipxl.resolver import pip_resolve


def compile(
    files_in: list[Path] | None = None,
    package_spec: list[str] | None = None,
    file_out: Path = Path("."),
    warn_non_requested_upgrade: bool = False,
) -> None:
    reqs, env = pip_resolve(files_in, package_spec)

    if file_out.exists() and warn_non_requested_upgrade:
        reqs_installed, _ = pip_resolve([file_out], no_deps=True)
        non_requested_packages_upgraded = _reconcile(reqs, reqs_installed)
        for r, current_version in non_requested_packages_upgraded:
            print(f"Upgrading non-requested dependency {r.name} from {current_version} to {r.version}")

    # for packages specified in the target(s), we do not have a specifier. We add the files. We do not add
    # the package_spec.
    if files_in:
        target_str = " ".join([f"-r {p}" for p in files_in])
        for r in reqs:
            if r.requested:
                r.required_by = {target_str: ""} | r.required_by

    text = _format_file(reqs, env)
    with file_out.open("w") as fp:
        fp.write(text)


def _reconcile(reqs: list[ReqFileEntry], reqs_installed: list[ReqFileEntry]) -> list[tuple[ReqFileEntry, str]]:
    non_requested_packages_upgraded = []
    non_requested_reqs = [r for r in reqs if not r.requested]
    for r in non_requested_reqs:
        for ri in reqs_installed:
            if ri.name == r.name and ri.version != r.version:
                non_requested_packages_upgraded.append((r, ri.version))
    return non_requested_packages_upgraded


def _format_file(reqs: list[ReqFileEntry], env: Environment) -> str:
    out = f"""# This file has been generated by pipxl {__version__}
#
# Environment at time of generation:
"""
    for name, val in env.__dict__.items():
        out += f"#\t{name}: {val}\n"

    out += "#\n\n"

    out += "\n".join([req.to_string() for req in reqs])
    out += "\n"

    return out
