"""The main module."""

import pathlib
import subprocess


def apply_name(name: str, description: str) -> None:
    """Apply a package name to this project."""
    projroot = pathlib.Path(__file__).parent.parent.parent
    lic = projroot / "LICENSE"
    pyproj = projroot / "pyproject.toml"
    readme = projroot / "README.rst"

    with lic.open("r+") as f:
        template = f.read()
        f.seek(0)
        content = template.replace("{{DESCRIPTION}}", description)
        f.write(content)
        f.truncate()

    with pyproj.open("r+") as f:
        template = f.read()
        f.seek(0)
        content = template.replace("{{PROJECT}}", name).replace("{{DESCRIPTION}}", description)
        f.write(content)
        f.truncate()

    with readme.open("r+") as f:
        template = f.read()
        f.seek(0)
        content = (
            template.replace("{{PROJECT}}", name)
            .replace("{{PROJECT_UNDERLINE}}", "#" * len(name))
            .replace("{{DESCRIPTION}}", description)
        )
        f.write(content)
        f.truncate()


def revert_apply_name() -> None:
    """Revert the application of a package name to this project."""
    projroot = pathlib.Path(__file__).parent.parent.parent

    subprocess.run(
        ["/usr/bin/git", "restore", "LICENSE", "pyproject.toml", "README.rst"],
        cwd=projroot,
        check=False,
    )


if __name__ == "__main__":
    import logging
    import sys

    if len(sys.argv) < 2:  # noqa: PLR2004
        logging.getLogger(__name__).error("bad args")
    else:
        _, name, *description = sys.argv

        if name == "--restore":
            revert_apply_name()
        elif len(description) != 1:
            logging.getLogger(__name__).error("bad args")
        else:
            apply_name(name, description[0])
