"""Disk storage used only on self-hosted VPS installs (LOCAL_STORAGE_DIR set)."""
from pathlib import Path


class DiskStore:
    def __init__(self, base: str):
        self.base = Path(base).resolve()

    def _path(self, key: str) -> Path:
        p = (self.base / key).resolve()
        if not str(p).startswith(str(self.base)):
            raise ValueError("bad path")
        return p

    def put(self, key: str, data: bytes, content_type: str) -> dict:
        p = self._path(key)
        p.parent.mkdir(parents=True, exist_ok=True)
        with open(p, "wb") as fh:
            fh.write(data)
        with open(f"{p}.type", "w") as fh:
            fh.write(content_type)
        return {"path": key, "size": len(data)}

    def get(self, key: str):
        p = self._path(key)
        t = Path(f"{p}.type")
        return p.read_bytes(), t.read_text() if t.exists() else "application/octet-stream"
