"""File scaffolding engine — creates practice files from templates."""

from __future__ import annotations

import importlib.resources
from pathlib import Path

from cde_onboard.constants import PRACTICE_DIR_NAME
from cde_onboard.models import ScaffoldFile


def _get_template_content(template_name: str) -> str:
    """Read a template file from the content/templates package."""
    templates = importlib.resources.files("cde_onboard.content") / "templates"
    template_path = templates / template_name
    return template_path.read_text(encoding="utf-8")


def scaffold_lesson(
    lesson_number: int,
    lesson_slug: str,
    files: list[ScaffoldFile],
    base_dir: Path | None = None,
) -> list[Path]:
    """Scaffold all files for a lesson into the practice directory.

    Creates files under:
        <base_dir>/cde-onboard-practice/lesson-NN-<slug>/<relative_path>

    Returns list of created file paths.
    """
    if base_dir is None:
        base_dir = Path.cwd()

    lesson_dir = base_dir / PRACTICE_DIR_NAME / f"lesson-{lesson_number:02d}-{lesson_slug}"
    lesson_root = lesson_dir.resolve()
    created: list[Path] = []

    for scaffold in files:
        try:
            content = _get_template_content(scaffold.template_name)
            relative_path = Path(scaffold.relative_path)
            if relative_path.is_absolute() or ".." in relative_path.parts:
                raise ValueError(
                    f"Invalid scaffold path '{scaffold.relative_path}'. "
                    "Paths must be relative and cannot contain '..'."
                )
            target = lesson_dir / relative_path
            target_resolved = target.resolve()
            try:
                target_resolved.relative_to(lesson_root)
            except ValueError as exc:
                raise ValueError(
                    f"Invalid scaffold path '{scaffold.relative_path}'. "
                    "Path must stay within the lesson directory."
                ) from exc
            target.parent.mkdir(parents=True, exist_ok=True)
            target.write_text(content, encoding="utf-8")
            created.append(target)
        except FileNotFoundError:
            raise FileNotFoundError(
                f"Template '{scaffold.template_name}' not found. "
                "The package may be corrupted — try reinstalling."
            )
        except OSError as e:
            raise OSError(
                f"Could not write '{scaffold.relative_path}': {e}. "
                "Check directory permissions and disk space."
            ) from e

    return created
