"""Local file store under ``SNAPFILE_STORAGE_DIR`` (TZ 2.10.1). S3 driver: iteration 2.

All writes are atomic (temp file in the target directory + ``os.replace``).
"""

from __future__ import annotations

import os
import shutil
import tempfile
from pathlib import Path

from django.conf import settings


class LocalStore:
    disk = "local"

    def __init__(self, root: Path | None = None) -> None:
        self.root = Path(root or settings.SNAPFILE_STORAGE_DIR)

    def path(self, rel: str) -> Path:
        p = (self.root / rel).resolve()
        if self.root.resolve() not in p.parents and p != self.root.resolve():
            raise ValueError("path escapes storage root")
        return p

    def write(self, rel: str, data: bytes) -> Path:
        target = self.path(rel)
        target.parent.mkdir(parents=True, exist_ok=True)
        fd, tmp = tempfile.mkstemp(dir=target.parent, prefix=".tmp-")
        try:
            with os.fdopen(fd, "wb") as f:
                f.write(data)
            os.replace(tmp, target)
        except BaseException:
            try:
                os.unlink(tmp)
            except OSError:
                pass
            raise
        return target

    def read(self, rel: str) -> bytes:
        return self.path(rel).read_bytes()

    def exists(self, rel: str) -> bool:
        return self.path(rel).exists()

    def delete(self, rel: str) -> None:
        try:
            self.path(rel).unlink()
        except FileNotFoundError:
            pass

    def delete_tree(self, rel: str) -> None:
        shutil.rmtree(self.path(rel), ignore_errors=True)


def store() -> LocalStore:
    return LocalStore()
