from pathlib import Path
import importlib.resources
import textwrap
import re
from .options import *


def write(path: Path, content: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(textwrap.dedent(content), encoding="utf-8")


def format_write(
    src: Path,
    dest: Path,
    naming: dict[list[str], list[str]],
    dargs: dict[str, str],
) -> None:
    """
    Read a file from the specified source path, apply formatting, and write to
    the specified destination path.

    Args:
        src (Path): The path to the input file.
        dest (Path): The output path.
        naming dict[str, str]: naming[INPUTs] are the input file names (required).
                               If defined, naming[RENAMES] are the output names
                               and must match the size of naming[INPUTS].
        dargs dict[str, str]: Formatting replacements.
    """
    assert "INPUTS" in naming, f"INPUTS must be defined"
    assert naming["INPUTS"], f"At least one input must be defined"

    for index, input in enumerate(naming["INPUTS"]):
        output = (
            naming["RENAMES"][index]
            if "RENAMES" in naming and naming["RENAMES"][index] != None
            else naming["INPUTS"][index]
        )
        file = importlib.resources.read_text(src, input)
        # Do this manually because ''.format() is even worse.
        for key, value in dargs.items():
            file = re.sub(f"{key}", f"{value}", file)
        write(dest / output, file)


def copy_resource(src: str, dest: Path) -> None:
    dest.parent.mkdir(parents=True, exist_ok=True)
    content = (
        importlib.resources.files("flecsi_sandbox._auxiliary")
        .joinpath(src)
        .read_text()
    )
    write(dest / src, content)
