import typer
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
import subprocess
from fapi.constants import TEMPLATES_DIR


def create_venv(project_dir: Path):
    typer.echo("🛠 Creating virtual environment...")
    subprocess.run(["python3", "-m", "venv", ".venv"], cwd=project_dir)


def req_installer(project_dir: Path):
    req_file = project_dir / "requirements.txt"
    pip_path = project_dir / ".venv" / "bin" / "pip"

    typer.echo("📦 Installing dependencies...")
    subprocess.run([str(pip_path), "install", "-r", str(req_file)])

def render_template(src, dest, context):
    env = Environment(loader=FileSystemLoader(TEMPLATES_DIR))
    template = env.get_template(src)
    rendered = template.render(**context)

    dest.parent.mkdir(parents=True, exist_ok=True)
    dest.write_text(rendered)

def ensure_fastapi_project():
    if not Path(".fastapi").exists():
        typer.echo("❌ This is not a FastAPI project generated by this CLI.")
        typer.echo("Hint: Run `fapi create <project-name>` first.")
        raise typer.Exit(1)
