"""sha-addressed store for preserved non-art post files.

Arbitrary binaries — never opened or validated as images. Parallels the
thumbnail store layout (/images/attachments/<sha[:3]>/<sha><ext>).
"""

import shutil
from pathlib import Path


class AttachmentStore:
    def __init__(self, images_root: Path):
        self.root = Path(images_root) / "attachments"

    def store(self, src: Path, sha256: str) -> str:
        """Copy src into the sha-addressed store; idempotent on sha.
        Returns the stored absolute path as a string."""
        ext = Path(src).suffix.lower()
        dest_dir = self.root / sha256[:3]
        dest_dir.mkdir(parents=True, exist_ok=True)
        dest = dest_dir / f"{sha256}{ext}"
        if dest.exists():
            return str(dest)
        partial = dest.with_suffix(dest.suffix + ".partial")
        shutil.copy2(src, partial)
        partial.rename(dest)
        return str(dest)
