"""Keep adapter backups out of Nitro/Vite scan roots.

Nuxt auto-imports ``server/utils``. A sibling ``p2hs-records.mjs.p2hs-local.bak``
is treated as a duplicate module and can win the build. Retire copies live under
``.p2hs/local-bak/`` instead.
"""
from __future__ import annotations

from pathlib import Path

BAK_ROOT = ".p2hs/local-bak"
_SCANNED_ROOTS = ("server", "functions")
_BAK_SUFFIX = ".p2hs-local.bak"


def bak_path(root: Path, rel: str) -> Path:
    return root / BAK_ROOT / rel.replace("\\", "/")


def copy_to_bak(root: Path, rel: str) -> str:
    src = root / rel
    dest = bak_path(root, rel)
    dest.parent.mkdir(parents=True, exist_ok=True)
    dest.write_bytes(src.read_bytes())
    return dest.relative_to(root).as_posix()


def move_to_bak(root: Path, rel: str) -> str:
    src = root / rel
    dest = bak_path(root, rel)
    dest.parent.mkdir(parents=True, exist_ok=True)
    if dest.exists():
        dest.unlink()
    src.replace(dest)
    return dest.relative_to(root).as_posix()


def purge_scanned_backups(root: Path) -> list[str]:
    """Delete leftover ``*.p2hs-local.bak`` files Nitro would bundle."""
    removed: list[str] = []
    for folder in _SCANNED_ROOTS:
        base = root / folder
        if not base.is_dir():
            continue
        for path in base.rglob("*"):
            if path.is_file() and path.name.endswith(_BAK_SUFFIX):
                removed.append(path.relative_to(root).as_posix())
                path.unlink()
    return removed
