from pathlib import Path
from jinja2 import Environment, FileSystemLoader
from briza.context import ProjectContext

BASE_DIR = Path(__file__).parent
TEMPLATES_DIR = BASE_DIR / "templates"

env = Environment(loader=FileSystemLoader(TEMPLATES_DIR))


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.")

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

    # Render templates
    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()


def render_template(template_name: str, output_path: Path, context: ProjectContext):
    template = env.get_template(template_name)
    rendered = template.render(**context.__dict__)
    output_path.write_text(rendered, encoding="utf-8")