"""
storage.py — where photo files live: this disk (`local`) or a bucket (`s3`, MinIO). Selected by STORAGE_BACKEND.

Why it exists: in 2026-10 the app server had almost no free disk and the MinIO box had 2.5 TB, so every photo
(originals, trash, previews, protected copies) moved to the bucket. Only incoming/ (FTP drop, read by the organizer
with OpenCV/EXIF and watched by watchdog) and a bounded cache stay on this disk.

Callers never see a filesystem path for a stored file: they handle a `Key`, a PurePosixPath whose first part is the
AREA (`photos/…` or `thumbs/…`), e.g. `photos/san-martin/1A/Student 3/DSC_0012.jpg`. `.name`, `.stem`, `.parent`
and `/` work as on a Path; anything that touches the bytes goes through this module. When a library needs a real
file (Pillow, OpenCV), `local_path(key)` gives one (the file itself in `local`, a cached copy in `s3`).

Rules that matter (each one is a bug S3 would otherwise introduce):
  - The modification time is the photo's ARRIVAL time (RGPD retention, search by date, last photo of a family).
    S3 resets LastModified on every upload and copy, so `s3` keeps the original mtime in the object metadata
    (`x-amz-meta-mtime`) AND in a MySQL index (`stored_objects`) which also answers every listing without a
    request to the bucket. `reconcile()` rebuilds the index from the bucket.
  - A move is copy + check + delete. If any step fails the source is untouched and an exception is raised: the
    organizer's `_move` turns it into False (see its docstring) and the photo stays in incoming.
  - A cached copy is named after the key AND the object's etag: a replaced object is never served stale.
  - The cache is bounded (STORAGE_CACHE_MB); the least recently used files go first. Paid downloads are streamed
    from the bucket and never go through it (a zip of originals would flush the previews everybody is looking at).
"""
from __future__ import annotations

import hashlib
import logging
import os
import shutil
import threading
import time
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from typing import Iterator, List, Optional

from core import config

logger = logging.getLogger(__name__)

AREAS = ("photos", "thumbs")
CHUNK = 1024 * 1024


class StorageError(Exception):
    """The storage refused or failed an operation (bucket unreachable, upload not verified…)."""


class Key(PurePosixPath):
    """Address of a stored file: `{area}/…`. A distinct class so a Key is never mistaken for a local Path (on
    Linux a PosixPath IS a PurePosixPath)."""

    @property
    def area(self) -> str:
        return self.parts[0] if self.parts else ""


def key(*parts: str) -> Key:
    k = Key(*parts)
    _check(k)
    return k


def _check(k: Key) -> None:
    if not isinstance(k, Key):
        raise TypeError(f"not a storage Key: {k!r}")
    if not k.parts or k.parts[0] not in AREAS or ".." in k.parts or k.is_absolute():
        raise ValueError(f"invalid storage key: {k!s}")


@dataclass
class ObjInfo:
    key: Key
    size: int
    mtime: float
    etag: str = ""

    @property
    def name(self) -> str:
        return self.key.name

    @property
    def stem(self) -> str:
        return self.key.stem

    @property
    def suffix(self) -> str:
        return self.key.suffix


# ─── Local backend: the files on this disk (behaviour before MinIO) ────────────

class LocalStorage:
    name = "local"

    def _root(self, area: str) -> Path:
        return config.PHOTOS_DIR if area == "photos" else config.THUMBS_DIR

    def path(self, k: Key) -> Path:
        _check(k)
        return self._root(k.area).joinpath(*k.parts[1:])

    def stat(self, k: Key) -> Optional[ObjInfo]:
        p = self.path(k)
        try:
            st = p.stat()
        except OSError:
            return None
        if not p.is_file():
            return None
        return ObjInfo(k, st.st_size, st.st_mtime)

    def is_dir(self, k: Key) -> bool:
        return self.path(k).is_dir()

    def files(self, k: Key) -> List[ObjInfo]:
        out = []
        try:
            for p in self.path(k).iterdir():
                try:
                    if p.is_file():
                        st = p.stat()
                        out.append(ObjInfo(k / p.name, st.st_size, st.st_mtime))
                except OSError:
                    continue
        except OSError:
            pass
        return out

    def dirs(self, k: Key) -> List[Key]:
        try:
            return [k / p.name for p in self.path(k).iterdir() if p.is_dir()]
        except OSError:
            return []

    def walk(self, k: Key) -> List[ObjInfo]:
        base = self.path(k)
        out = []
        if not base.is_dir():
            return out
        for p in base.rglob("*"):
            try:
                if p.is_file():
                    st = p.stat()
                    out.append(ObjInfo(Key(k, *p.relative_to(base).parts), st.st_size, st.st_mtime))
            except OSError:
                continue
        return out

    def read_bytes(self, k: Key) -> bytes:
        return self.path(k).read_bytes()

    def write_bytes(self, k: Key, data: bytes, mtime: Optional[float] = None) -> None:
        p = self.path(k)
        p.parent.mkdir(parents=True, exist_ok=True)
        tmp = p.with_name(f".{p.name}.{os.getpid()}.{threading.get_ident()}.tmp")
        tmp.write_bytes(data)
        if mtime is not None:
            os.utime(tmp, (mtime, mtime))
        os.replace(tmp, p)

    def put_file(self, src: Path, k: Key, mtime: Optional[float] = None) -> None:
        p = self.path(k)
        p.parent.mkdir(parents=True, exist_ok=True)
        tmp = p.with_name(f".{p.name}.{os.getpid()}.{threading.get_ident()}.tmp")
        shutil.copyfile(src, tmp)
        if mtime is not None:
            os.utime(tmp, (mtime, mtime))
        os.replace(tmp, p)

    def produce(self, k: Key, write, mtime: Optional[float] = None) -> None:
        p = self.path(k)
        p.parent.mkdir(parents=True, exist_ok=True)
        tmp = p.with_name(f".{p.name}.{os.getpid()}.{threading.get_ident()}.tmp")
        try:
            write(tmp)
            if mtime is not None:
                os.utime(tmp, (mtime, mtime))
            os.replace(tmp, p)
        finally:
            tmp.unlink(missing_ok=True)

    def ingest(self, src: Path, k: Key) -> None:
        p = self.path(k)
        p.parent.mkdir(parents=True, exist_ok=True)
        shutil.move(str(src), str(p))          # a rename on one volume, copy2 (mtime kept) across volumes

    def local_path(self, k: Key) -> Path:
        p = self.path(k)
        if not p.is_file():
            raise FileNotFoundError(str(k))
        return p

    def move(self, src: Key, dst: Key) -> None:
        s, d = self.path(src), self.path(dst)
        if not s.is_file():
            raise FileNotFoundError(str(src))
        d.parent.mkdir(parents=True, exist_ok=True)
        shutil.move(str(s), str(d))

    def move_tree(self, src: Key, dst: Key) -> int:
        s, d = self.path(src), self.path(dst)
        if not s.is_dir():
            return 0
        count = sum(1 for f in s.rglob("*") if f.is_file())
        if not d.exists():
            d.parent.mkdir(parents=True, exist_ok=True)
            shutil.move(str(s), str(d))
            return count
        for info in self.walk(src):                       # merge into an existing folder, never overwrite
            target = Key(dst, *info.key.parts[len(src.parts):])
            if self.path(target).exists():
                raise FileExistsError(str(target))
            self.move(info.key, target)
        shutil.rmtree(s, ignore_errors=True)
        return count

    def touch(self, k: Key, mtime: float) -> None:
        os.utime(self.local_path(k), (mtime, mtime))

    def delete(self, k: Key) -> None:
        self.path(k).unlink(missing_ok=True)

    def delete_tree(self, k: Key) -> int:
        p = self.path(k)
        if not p.is_dir():
            return 0
        count = sum(1 for f in p.rglob("*") if f.is_file())
        shutil.rmtree(p, ignore_errors=True)
        return count

    def mkdir(self, k: Key) -> None:
        self.path(k).mkdir(parents=True, exist_ok=True)

    def prune_empty(self, k: Key, keep_depth: int = 0) -> None:
        base = self.path(k)
        if not base.is_dir():
            return
        for d in sorted(base.rglob("*"), reverse=True):        # bottom-up
            if d.is_dir() and len(d.relative_to(base).parts) > keep_depth:
                try:
                    d.rmdir()
                except OSError:
                    pass

    def iter_chunks(self, k: Key, chunk: int = CHUNK) -> Iterator[bytes]:
        with open(self.local_path(k), "rb") as fh:
            while True:
                b = fh.read(chunk)
                if not b:
                    return
                yield b

    def usage(self, k: Key) -> tuple[int, int]:
        files = self.walk(k)
        return len(files), sum(f.size for f in files)

    def check(self) -> None:
        for area in AREAS:
            self._root(area).mkdir(parents=True, exist_ok=True)

    def reconcile(self) -> dict:
        return {}


# ─── Local cache of bucket objects (s3 only) ──────────────────────────────────

class _Cache:
    """Files named `{sha1(key)}-{etag}{suffix}` in STORAGE_CACHE_DIR. Bounded: when the total passes the limit
    the least recently used go (the access time is the mtime, touched on every hit: atime is often disabled)."""

    def __init__(self, root: Path, limit_bytes: int):
        self.root = root
        self.limit = max(limit_bytes, 16 * 1024 * 1024)
        self._added = 0
        self._lock = threading.Lock()

    def path_for(self, k: Key, etag: str) -> Path:
        h = hashlib.sha1(str(k).encode()).hexdigest()
        return self.root / h[:2] / f"{h}-{(etag or 'x').strip(chr(34))[:40]}{k.suffix.lower()}"

    def get(self, k: Key, etag: str) -> Optional[Path]:
        p = self.path_for(k, etag)
        try:
            os.utime(p)
            return p
        except OSError:
            return None

    def adopt(self, tmp: Path, k: Key, etag: str) -> Path:
        """Move a complete file into the cache (atomic: a reader never sees half a file)."""
        p = self.path_for(k, etag)
        p.parent.mkdir(parents=True, exist_ok=True)
        size = tmp.stat().st_size
        os.replace(tmp, p)
        for old in p.parent.glob(f"{p.name.split('-', 1)[0]}-*"):   # older versions of the same key
            if old != p:
                old.unlink(missing_ok=True)
        with self._lock:
            self._added += size
            sweep = self._added > self.limit // 20
            if sweep:
                self._added = 0
        if sweep:
            self.sweep()
        return p

    def tmp(self) -> Path:
        self.root.mkdir(parents=True, exist_ok=True)
        return self.root / f".dl-{os.getpid()}-{threading.get_ident()}-{time.monotonic_ns()}.tmp"

    def forget(self, k: Key) -> None:
        h = hashlib.sha1(str(k).encode()).hexdigest()
        for old in (self.root / h[:2]).glob(f"{h}-*"):
            old.unlink(missing_ok=True)

    def sweep(self) -> int:
        files = []
        total = 0
        for p in self.root.rglob("*"):
            try:
                if p.is_file():
                    st = p.stat()
                    if p.name.startswith(".dl-") and time.time() - st.st_mtime < 3600:
                        continue                                       # a download in progress
                    files.append((st.st_mtime, st.st_size, p))
                    total += st.st_size
            except OSError:
                continue
        removed = 0
        if total <= self.limit:
            return 0
        target = int(self.limit * 0.8)
        for _mtime, size, p in sorted(files):
            if total <= target:
                break
            try:
                p.unlink()
                total -= size
                removed += 1
            except OSError:
                continue
        logger.info("Storage cache: %d file(s) evicted, %.0f MB kept", removed, total / 1048576)
        return removed

    def size(self) -> int:
        return sum(p.stat().st_size for p in self.root.rglob("*") if p.is_file())


# ─── S3 backend (MinIO) ───────────────────────────────────────────────────────

def _sha1(s: str) -> str:
    return hashlib.sha1(s.encode()).hexdigest()


def _like_prefix(k: Key) -> str:
    s = f"{k}/"
    return s.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"


class S3Storage:
    name = "s3"

    def __init__(self, client=None, bucket: Optional[str] = None, table: str = "stored_objects",
                 cache_dir: Optional[Path] = None):
        self._client = client
        self._client_lock = threading.Lock()
        self.bucket = bucket or config.S3_BUCKET
        self.table = table                       # tests give each isolated store its own index table
        self.cache = _Cache(cache_dir or config.STORAGE_CACHE_DIR, config.STORAGE_CACHE_MB * 1024 * 1024)

    # ── plumbing ──
    @property
    def client(self):
        if self._client is None:
            with self._client_lock:
                if self._client is None:
                    import boto3
                    from botocore.config import Config
                    self._client = boto3.client(
                        "s3", endpoint_url=config.S3_ENDPOINT_URL or None, region_name=config.S3_REGION,
                        aws_access_key_id=config.S3_ACCESS_KEY or None,
                        aws_secret_access_key=config.S3_SECRET_KEY or None,
                        config=Config(s3={"addressing_style": "path"}, signature_version="s3v4",
                                      retries={"max_attempts": 5, "mode": "standard"},
                                      connect_timeout=5, read_timeout=60, max_pool_connections=32))
        return self._client

    @staticmethod
    def _db():
        from core.db import get_db
        return get_db()

    def init_index(self) -> None:
        from core.db import TABLE_OPTIONS
        with self._db() as conn:
            # utf8mb4_bin: keys are case-sensitive in S3, "1A/Student 1" and "1a/student 1" are two objects.
            conn.execute(f"""
            CREATE TABLE IF NOT EXISTS {self.table} (
                khash       CHAR(40) NOT NULL PRIMARY KEY,
                obj_key     VARCHAR(1024) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
                parent_hash CHAR(40) NOT NULL,
                size        BIGINT NOT NULL DEFAULT 0,
                mtime       DOUBLE NOT NULL DEFAULT 0,
                etag        VARCHAR(80) NOT NULL DEFAULT '',
                updated_at  DOUBLE NOT NULL DEFAULT 0,
                KEY idx_parent (parent_hash),
                KEY idx_key (obj_key(191))
            ) {TABLE_OPTIONS}""")
            conn.commit()

    def _index_put(self, k: Key, size: int, mtime: float, etag: str) -> None:
        with self._db() as conn:
            conn.execute(f"INSERT OR REPLACE INTO {self.table} (khash, obj_key, parent_hash, size, mtime, etag, "
                         "updated_at) VALUES (?,?,?,?,?,?,?)",
                         (_sha1(str(k)), str(k), _sha1(str(k.parent)), size, mtime, etag, time.time()))
            conn.commit()

    def _index_drop(self, k: Key) -> None:
        with self._db() as conn:
            conn.execute(f"DELETE FROM {self.table} WHERE khash=?", (_sha1(str(k)),))
            conn.commit()

    @staticmethod
    def _info(r) -> ObjInfo:
        return ObjInfo(Key(r["obj_key"]), int(r["size"]), float(r["mtime"]), r["etag"])

    @staticmethod
    def _etag(resp) -> str:
        return (resp.get("ETag") or "").strip('"')

    @staticmethod
    def _missing(exc) -> bool:
        code = str(getattr(exc, "response", {}).get("Error", {}).get("Code", ""))
        return code in ("404", "NoSuchKey", "NotFound")

    # ── reads (index) ──
    def stat(self, k: Key) -> Optional[ObjInfo]:
        _check(k)
        with self._db() as conn:
            r = conn.execute(f"SELECT * FROM {self.table} WHERE khash=?", (_sha1(str(k)),)).fetchone()
        return self._info(r) if r else None

    def is_dir(self, k: Key) -> bool:
        _check(k)
        with self._db() as conn:
            return bool(conn.execute(f"SELECT 1 FROM {self.table} WHERE obj_key LIKE ? LIMIT 1",
                                     (_like_prefix(k),)).fetchone())

    def files(self, k: Key) -> List[ObjInfo]:
        _check(k)
        with self._db() as conn:
            rows = conn.execute(f"SELECT * FROM {self.table} WHERE parent_hash=?", (_sha1(str(k)),)).fetchall()
        return [self._info(r) for r in rows]

    def dirs(self, k: Key) -> List[Key]:
        _check(k)
        start = len(str(k)) + 2
        with self._db() as conn:
            rows = conn.execute(
                f"SELECT DISTINCT SUBSTRING_INDEX(SUBSTRING(obj_key, ?), '/', 1) AS d FROM {self.table} "
                "WHERE obj_key LIKE ? AND LOCATE('/', obj_key, ?) > 0", (start, _like_prefix(k), start)).fetchall()
        return sorted(k / r["d"] for r in rows if r["d"])

    def walk(self, k: Key) -> List[ObjInfo]:
        _check(k)
        with self._db() as conn:
            rows = conn.execute(f"SELECT * FROM {self.table} WHERE obj_key LIKE ?", (_like_prefix(k),)).fetchall()
        return [self._info(r) for r in rows]

    def usage(self, k: Key) -> tuple[int, int]:
        _check(k)
        with self._db() as conn:
            r = conn.execute(f"SELECT COUNT(*) AS n, COALESCE(SUM(size),0) AS b FROM {self.table} WHERE obj_key LIKE ?",
                             (_like_prefix(k),)).fetchone()
        return int(r["n"]), int(r["b"])

    # ── bytes ──
    def local_path(self, k: Key) -> Path:
        info = self.stat(k)
        if info is None:
            raise FileNotFoundError(str(k))
        hit = self.cache.get(k, info.etag)
        if hit is not None:
            return hit
        tmp = self.cache.tmp()
        try:
            self.client.download_file(self.bucket, str(k), str(tmp))
        except Exception as exc:
            tmp.unlink(missing_ok=True)
            if self._missing(exc):
                self._index_drop(k)
                raise FileNotFoundError(str(k)) from exc
            raise StorageError(f"download {k}: {exc}") from exc
        os.utime(tmp, (info.mtime, info.mtime))
        p = self.cache.adopt(tmp, k, info.etag)
        os.utime(p)
        return p

    def read_bytes(self, k: Key) -> bytes:
        return self.local_path(k).read_bytes()

    def iter_chunks(self, k: Key, chunk: int = CHUNK) -> Iterator[bytes]:
        if self.stat(k) is None:
            raise FileNotFoundError(str(k))
        try:
            body = self.client.get_object(Bucket=self.bucket, Key=str(k))["Body"]
        except Exception as exc:
            if self._missing(exc):
                raise FileNotFoundError(str(k)) from exc
            raise StorageError(f"get {k}: {exc}") from exc
        try:
            while True:
                b = body.read(chunk)
                if not b:
                    return
                yield b
        finally:
            body.close()

    # ── writes ──
    def _upload(self, src: Path, k: Key, mtime: float) -> str:
        size = src.stat().st_size
        try:
            self.client.upload_file(str(src), self.bucket, str(k),
                                    ExtraArgs={"Metadata": {"mtime": repr(float(mtime))}})
            head = self.client.head_object(Bucket=self.bucket, Key=str(k))
        except Exception as exc:
            raise StorageError(f"upload {k}: {exc}") from exc
        if int(head.get("ContentLength", -1)) != size:
            raise StorageError(f"upload {k}: {head.get('ContentLength')} bytes stored, {size} sent")
        etag = self._etag(head)
        self._index_put(k, size, mtime, etag)
        return etag

    def put_file(self, src: Path, k: Key, mtime: Optional[float] = None) -> None:
        _check(k)
        self._upload(src, k, time.time() if mtime is None else mtime)

    def write_bytes(self, k: Key, data: bytes, mtime: Optional[float] = None) -> None:
        _check(k)
        tmp = self.cache.tmp()
        tmp.write_bytes(data)
        try:
            etag = self._upload(tmp, k, time.time() if mtime is None else mtime)
            self.cache.adopt(tmp, k, etag)              # what was just written is usually read right after
        finally:
            tmp.unlink(missing_ok=True)

    def produce(self, k: Key, write, mtime: Optional[float] = None) -> None:
        _check(k)
        tmp = self.cache.tmp()
        try:
            write(tmp)
            etag = self._upload(tmp, k, time.time() if mtime is None else mtime)
            self.cache.adopt(tmp, k, etag)              # a derivative is served right after it is made
        finally:
            tmp.unlink(missing_ok=True)

    def ingest(self, src: Path, k: Key) -> None:
        """A local file (incoming/) INTO the bucket: upload, verify, then delete the local file. Keeps its mtime.
        If the upload is not verified the local file is untouched and StorageError is raised."""
        _check(k)
        self._upload(src, k, src.stat().st_mtime)
        src.unlink()

    def move(self, src: Key, dst: Key) -> None:
        _check(src)
        _check(dst)
        info = self.stat(src)
        if info is None:
            raise FileNotFoundError(str(src))
        try:
            self.client.copy_object(Bucket=self.bucket, Key=str(dst), MetadataDirective="COPY",
                                    CopySource={"Bucket": self.bucket, "Key": str(src)})
            head = self.client.head_object(Bucket=self.bucket, Key=str(dst))
        except Exception as exc:
            if self._missing(exc):
                self._index_drop(src)
                raise FileNotFoundError(str(src)) from exc
            raise StorageError(f"copy {src} -> {dst}: {exc}") from exc
        if int(head.get("ContentLength", -1)) != info.size:
            raise StorageError(f"copy {src} -> {dst}: size mismatch")
        self._index_put(dst, info.size, info.mtime, self._etag(head))
        self.delete(src)

    def move_tree(self, src: Key, dst: Key) -> int:
        items = self.walk(src)
        for info in items:                                 # never overwrite (same rule as the local backend)
            if self.stat(Key(dst, *info.key.parts[len(src.parts):])) is not None:
                raise FileExistsError(str(dst))
        done: list[tuple[Key, Key]] = []
        try:
            for info in items:
                target = Key(dst, *info.key.parts[len(src.parts):])
                self.move(info.key, target)
                done.append((info.key, target))
        except Exception:
            # Half a folder moved is worse than none (a renamed class would point at a folder with half its photos):
            # put back what moved, then let the caller's transaction roll back.
            for orig, target in reversed(done):
                try:
                    self.move(target, orig)
                except Exception as exc:
                    logger.error("move_tree rollback: %s stays at %s (%s)", orig, target, exc)
            raise
        return len(items)

    def touch(self, k: Key, mtime: float) -> None:
        """Set the arrival time of a stored object (migration of old photos, tests)."""
        info = self.stat(k)
        if info is None:
            raise FileNotFoundError(str(k))
        try:
            self.client.copy_object(Bucket=self.bucket, Key=str(k), CopySource={"Bucket": self.bucket, "Key": str(k)},
                                    MetadataDirective="REPLACE", Metadata={"mtime": repr(float(mtime))})
            head = self.client.head_object(Bucket=self.bucket, Key=str(k))
        except Exception as exc:
            raise StorageError(f"touch {k}: {exc}") from exc
        self._index_put(k, info.size, mtime, self._etag(head))

    def delete(self, k: Key) -> None:
        _check(k)
        try:
            self.client.delete_object(Bucket=self.bucket, Key=str(k))
        except Exception as exc:
            if not self._missing(exc):
                raise StorageError(f"delete {k}: {exc}") from exc
        self._index_drop(k)
        self.cache.forget(k)

    def delete_tree(self, k: Key) -> int:
        items = self.walk(k)
        for i in range(0, len(items), 1000):
            batch = items[i:i + 1000]
            try:
                self.client.delete_objects(Bucket=self.bucket, Delete={
                    "Objects": [{"Key": str(x.key)} for x in batch], "Quiet": True})
            except Exception as exc:
                raise StorageError(f"delete {k}/: {exc}") from exc
            with self._db() as conn:
                conn.executemany(f"DELETE FROM {self.table} WHERE khash=?", [(_sha1(str(x.key)),) for x in batch])
                conn.commit()
            for x in batch:
                self.cache.forget(x.key)
        return len(items)

    def mkdir(self, k: Key) -> None:
        """A bucket has no folders: a folder exists while it holds a file."""

    def prune_empty(self, k: Key, keep_depth: int = 0) -> None:
        """Nothing to prune: an empty folder does not exist in a bucket."""

    def sweep_cache(self) -> int:
        return self.cache.sweep()

    # ── health / repair ──
    def check(self) -> None:
        try:
            self.client.head_bucket(Bucket=self.bucket)
        except Exception as exc:
            raise StorageError(f"bucket {self.bucket!r} at {config.S3_ENDPOINT_URL}: {exc}") from exc
        self.init_index()
        config.STORAGE_CACHE_DIR.mkdir(parents=True, exist_ok=True)

    def reconcile(self) -> dict:
        """Make the index say what the bucket holds: rows for objects nobody indexed (a crash between upload and
        insert), no rows for objects that are gone. The bucket is the truth; the mtime comes from its metadata."""
        seen: dict[str, dict] = {}
        paginator = self.client.get_paginator("list_objects_v2")
        for page in paginator.paginate(Bucket=self.bucket):
            for o in page.get("Contents", []):
                if o["Key"].split("/", 1)[0] in AREAS:
                    seen[o["Key"]] = o
        with self._db() as conn:
            rows = {r["obj_key"]: r for r in conn.execute(f"SELECT obj_key, size, etag FROM {self.table}")}
        added = removed = fixed = 0
        for k, o in seen.items():
            r = rows.get(k)
            etag = (o.get("ETag") or "").strip('"')
            if r is not None and int(r["size"]) == int(o["Size"]) and r["etag"] == etag:
                continue
            try:
                head = self.client.head_object(Bucket=self.bucket, Key=k)
                mtime = float(head.get("Metadata", {}).get("mtime") or o["LastModified"].timestamp())
            except Exception as exc:
                logger.warning("reconcile: cannot read %s: %s", k, exc)
                continue
            self._index_put(Key(k), int(o["Size"]), mtime, etag)
            if r is None:
                added += 1
            else:
                fixed += 1
        for k in rows:
            if k not in seen:
                self._index_drop(Key(k))
                removed += 1
        if added or removed or fixed:
            logger.warning("Storage index repaired: %d added, %d removed, %d fixed", added, removed, fixed)
        return {"added": added, "removed": removed, "fixed": fixed, "objects": len(seen)}


# ─── Active backend ───────────────────────────────────────────────────────────

_backend = None
_backend_lock = threading.Lock()


def backend():
    global _backend
    if _backend is None:
        with _backend_lock:
            if _backend is None:
                _backend = S3Storage() if config.STORAGE_BACKEND == "s3" else LocalStorage()
    return _backend


def set_backend(b) -> None:
    """Tests (and the migration script) pick the backend explicitly."""
    global _backend
    with _backend_lock:
        _backend = b


def is_remote() -> bool:
    return backend().name == "s3"


def init() -> None:
    """Startup: the bucket must answer (and the index exist) before anything is organized or served."""
    backend().check()


# Thin module-level API (what the services call).
def stat(k: Key) -> Optional[ObjInfo]: return backend().stat(k)
def exists(k: Key) -> bool: return backend().stat(k) is not None
def is_dir(k: Key) -> bool: return backend().is_dir(k)
def files(k: Key) -> List[ObjInfo]: return backend().files(k)
def dirs(k: Key) -> List[Key]: return backend().dirs(k)
def walk(k: Key) -> List[ObjInfo]: return backend().walk(k)
def usage(k: Key) -> tuple[int, int]: return backend().usage(k)
def local_path(k: Key) -> Path: return backend().local_path(k)
def read_bytes(k: Key) -> bytes: return backend().read_bytes(k)
def read_text(k: Key) -> str: return backend().read_bytes(k).decode("utf-8")
def write_bytes(k: Key, data: bytes, mtime: Optional[float] = None) -> None: backend().write_bytes(k, data, mtime)
def write_text(k: Key, text: str) -> None: backend().write_bytes(k, text.encode("utf-8"))
def put_file(src: Path, k: Key, mtime: Optional[float] = None) -> None: backend().put_file(src, k, mtime)
def ingest(src: Path, k: Key) -> None: backend().ingest(src, k)


def produce(k: Key, write, mtime: Optional[float] = None) -> None:
    """Make a new stored file: `write(tmp)` writes it to a local temporary path (Pillow, bytes…), then it is
    stored atomically under `k` (a reader never sees half a file). The temporary file is always removed."""
    backend().produce(k, write, mtime)
def move(src: Key, dst: Key) -> None: backend().move(src, dst)
def move_tree(src: Key, dst: Key) -> int: return backend().move_tree(src, dst)
def delete(k: Key) -> None: backend().delete(k)
def touch(k: Key, mtime: float) -> None: backend().touch(k, mtime)
def delete_tree(k: Key) -> int: return backend().delete_tree(k)
def mkdir(k: Key) -> None: backend().mkdir(k)
def iter_chunks(k: Key, chunk: int = CHUNK) -> Iterator[bytes]: return backend().iter_chunks(k, chunk)
def reconcile() -> dict: return backend().reconcile()
def prune_empty(k: Key, keep_depth: int = 0) -> None: backend().prune_empty(k, keep_depth)
