from pathlib import Path
from importlib import resources
from jinja2 import Environment, BaseLoader
from briza.context import ProjectContext

env = Environment(loader=BaseLoader())


def render_template(template_name: str, output_path: Path, context: ProjectContext):
    template_text = (
        resources.files("briza.templates")
        .joinpath(template_name)
        .read_text(encoding="utf-8")
    )

    template = env.from_string(template_text)
    rendered = template.render(**context.__dict__)

    output_path.write_text(rendered, encoding="utf-8")


def create_project(name: str):
    package_name = name.replace("-", "_")

    context = ProjectContext(project_name=name, package_name=package_name)

    project_root = Path.cwd() / name

    if project_root.exists():
        raise FileExistsError(f"Directory '{name}' already exists.")

    (project_root / "src" / package_name).mkdir(parents=True)
    (project_root / "tests").mkdir()

    render_template("pyproject.toml.j2", project_root / "pyproject.toml", context)
    render_template("README.md.j2", project_root / "README.md", context)
    render_template(
        "main.py.j2",
        project_root / "src" / package_name / "main.py",
        context,
    )
    render_template(
        "test_main.py.j2",
        project_root / "tests" / "test_main.py",
        context,
    )

    (project_root / "src" / package_name / "__init__.py").touch()