"""Patch applier — safely edits files with backup support."""

from __future__ import annotations

import logging
import shutil
from pathlib import Path

logger = logging.getLogger(__name__)


def apply_patch(
    file_path: str | Path,
    original_snippet: str,
    patched_snippet: str,
    *,
    create_backup: bool = True,
) -> bool:
    """Replace *original_snippet* with *patched_snippet* in *file_path*.

    Steps
    -----
    1. Create a ``.bak`` backup of the original file (unless disabled).
    2. Read the file, locate the snippet, and replace.
    3. Write the updated content back.

    Returns
    -------
    bool
        ``True`` if the patch was applied successfully.
    """
    path = Path(file_path)

    if not path.is_file():
        logger.error("Patch target does not exist: %s", path)
        return False

    content = path.read_text(encoding="utf-8", errors="replace")

    if original_snippet not in content:
        logger.error(
            "Original snippet not found in %s — patch cannot be applied.", path
        )
        return False

    # 1. Backup
    if create_backup:
        backup = path.with_suffix(path.suffix + ".bak")
        shutil.copy2(path, backup)
        logger.info("Backup created: %s", backup)

    # 2. Replace
    updated = content.replace(original_snippet, patched_snippet, 1)

    # 3. Write
    path.write_text(updated, encoding="utf-8")
    logger.info("Patch applied to %s", path)
    return True
