# 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("."),
) -> None:
    reqs, env = pip_resolve(files_in, package_spec)

    # 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 is not None) and len(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 _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
