import re
import sys
from importlib import resources
from pathlib import Path

from jinja2 import Template

from ssb_pubmd import templates
from ssb_pubmd.environment import cms_environment


def create_project(article_title: str) -> str:
    """Creates a project folder with a template article file.

    The folder and file name is set to a sanitized version of the given article name.
    """
    name = _sanitize_name(article_title)
    project_folder = Path.cwd() / name

    if project_folder.exists():
        print(f"Error: Folder '{name}' already exists")
        sys.exit(1)

    project_folder.mkdir()

    _create_gitignore(project_folder)
    _create_template_article(article_title, project_folder, name)

    return name


def _create_gitignore(project_folder: Path) -> None:
    """Adds a .gitignore file to the project folder.

    Prevents temporary notebooks generated by quarto to be included in version control.
    """
    with open(project_folder / ".gitignore", mode="x") as file:
        file.write("*.quarto_ipynb")


def _create_template_article(
    article_title: str, project_folder: Path, filename: str
) -> None:
    template_destination = project_folder / f"{filename}.qmd"

    with resources.open_text(templates, "quarto.qmd") as file:
        raw_template = file.read()

    rendered_template = Template(raw_template).render(
        virtual_environment_name=Path(sys.prefix).parent.name,
        article_title=article_title,
        filepath=template_destination,
        cms_admin_url=cms_environment.base_url + cms_environment.admin_path,
        project_folder=template_destination.parent.name,
        filename=template_destination.name,
    )
    template_destination.write_text(rendered_template)


def _sanitize_name(name: str) -> str:
    name = name.lower()
    name = re.sub(r"[ _]+", "-", name)
    name = re.sub(r"[^a-z0-9-]", "", name)
    name = re.sub(r"-{2,}", "-", name)
    return name.strip("-")
