"""Rename planning operations."""

from __future__ import annotations

from pathlib import Path
from typing import Any

from cascade_fm.core.cache.cache_none import NoCacheMixin
from cascade_fm.operations.base import CommitIntent, Operation


class RenamePattern(NoCacheMixin, Operation):
    """Plan file renaming using a string template."""

    @property
    def name(self) -> str:
        return "rename_pattern"

    @property
    def label(self) -> str:
        return "Rename"

    @property
    def description(self) -> str:
        return "Create planned target paths using {name}, {ext}, {index}"

    def _can_execute_without_params(self) -> bool:
        return True

    @property
    def commit_intent(self) -> CommitIntent:
        """Rename is virtual and commits via planned output names."""
        return CommitIntent.PLANNED_OUTPUT_NAMES

    def _execute_impl(self, files: list[Path], **params: Any) -> list[Path]:
        pattern = params.get("pattern", "{name}")
        planned_paths: list[Path] = []
        for index, file_path in enumerate(files, start=1):
            stem = file_path.stem
            ext = file_path.suffix.lstrip(".")
            rendered = pattern.format(name=stem, ext=ext, index=index)

            if file_path.suffix and "." not in Path(rendered).name:
                rendered = f"{rendered}{file_path.suffix}"

            planned_paths.append(file_path.parent / rendered)

        return planned_paths

    def validate_params(self, **params: Any) -> tuple[bool, str | None]:
        pattern = params.get("pattern", "{name}")

        if not isinstance(pattern, str):
            return False, "pattern must be a string"

        try:
            pattern.format(name="example", ext="txt", index=1)
        except Exception as error:
            return False, f"Invalid pattern: {error}"

        return True, None
