import pathlib
import typing as T

from .pkgconf_cache import INITPY_VARNAME
from .util import relpath_walk_up


def make_pc_file(
    project_root: pathlib.Path,
    pcfile: pathlib.Path,
    pc_install_path: pathlib.Path,
    name: str,
    desc: str,
    version: str,
    includes: T.List[str],
    depends: T.List[str],
    libinit_py: T.Optional[str],
    generator_name: str,
):

    pc_content = [
        f"# automatically generated by {generator_name}",
        "prefix=${pcfiledir}",
    ]

    if libinit_py:
        pc_content.append(f"{INITPY_VARNAME}={libinit_py}")

    cflags = ["-I${prefix}"]

    for i, inc in enumerate(includes):
        includedir = project_root / pathlib.PurePosixPath(inc)
        rel = relpath_walk_up(includedir, pc_install_path)
        pc_content.append(f"inc{i}=${{prefix}}/{rel.as_posix()}")
        cflags.append(f"-I${{inc{i}}}")

    pc_content += [
        "",
        f"Name: {name}",
        f"Description: {desc}",
        f"Version: {version}",
        "Cflags: " + " ".join(cflags),
    ]

    if depends:
        requires = " ".join(depends)
        pc_content.append(f"Requires: {requires}")

    pc_content.append("")

    pcfile.write_text("\n".join(pc_content), encoding="utf-8")
