from __future__ import annotations

from importlib import resources

from .models import PreferenceTier, ProjectType


def _tier_filename(tier: PreferenceTier) -> str:
    return tier.value + ".md"


def get_template_content(project_type: ProjectType, tier: PreferenceTier) -> str:
    """Load a bundled skill template by project type and preference tier."""
    tier_file = _tier_filename(tier)
    ref = resources.files("msl") / "skills" / project_type.value / tier_file
    return ref.read_text(encoding="utf-8")


def render_template(
    content: str,
    context: dict[str, str],
    frameworks: list[str] | None = None,
    scan_context: dict[str, str] | None = None,
) -> str:
    """Replace {{key}} placeholders and append detected-context section."""
    for key, value in context.items():
        content = content.replace("{{" + key + "}}", str(value))

    # Append a project-specific context section if we have scan data
    if scan_context or frameworks:
        content += "\n\n---\n\n## Project Context (auto-detected)\n\n"
        if scan_context:
            for key, value in scan_context.items():
                if value:
                    content += f"- **{key}**: {value}\n"
        if frameworks:
            content += f"- **Stack**: {', '.join(frameworks)}\n"
        content += "\n> This section was auto-generated by `msl` based on project scanning.\n> Adjust it to match your current needs.\n"

    return content
