"""Template deploy mapping and refresh logic."""

from __future__ import annotations

import shutil
from pathlib import Path

from ievo.marketplace import bundled_template_path

# (bundled_filename, project_relative_destination)
TEMPLATE_MAP: list[tuple[str, str]] = [
    ("iEVO.md", ".ievo/iEVO.md"),
    ("REQ_TEMPLATE.md", "spec/templates/REQ_TEMPLATE.md"),
    ("CHANGE_REQUEST_TEMPLATE.md", "spec/templates/CR_TEMPLATE.md"),
    ("QUESTION_TEMPLATE.md", "spec/templates/QUESTION_TEMPLATE.md"),
    ("PLAN_TEMPLATE.md", "spec/templates/PLAN_TEMPLATE.md"),
    ("ACCEPTANCE_REPORT_TEMPLATE.md", "spec/templates/ACCEPTANCE_REPORT_TEMPLATE.md"),
    ("PROPOSAL_TEMPLATE.md", "spec/templates/PROPOSAL_TEMPLATE.md"),
]


def refresh_templates(root: Path, cli_version: str) -> int:
    """Copy all bundled templates to the project and update cli_version.

    Returns the number of template files actually copied.
    """
    from ievo.core.project import ProjectManifest

    count = 0
    for bundled_name, dest_rel in TEMPLATE_MAP:
        src = bundled_template_path(bundled_name)
        if src is None:
            continue
        dest = root / dest_rel
        dest.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(src, dest)
        count += 1

    # Update manifest cli_version
    manifest = ProjectManifest.load(root)
    manifest.cli_version = cli_version
    manifest.save(root)

    return count
