"""
zip_stream.py — a zip built WHILE it is sent, from files that live in the photo storage.

Nothing is written to this disk (the app server has little room since the photos moved to MinIO), so a family's
download or the lab's folder of an order never waits for the whole archive. Deflate level 1: a stored entry in a
streamed zip needs a data descriptor that some unzip tools refuse, and JPEGs barely shrink anyway.
"""
import time
import zipfile
from typing import Callable
from urllib.parse import quote

from core import storage
from core.storage import Key


class ZipSink:
    """Write-only, non-seekable target for zipfile: what it writes is handed out in chunks as the zip is built."""

    def __init__(self):
        self.buf = bytearray()

    def write(self, b) -> int:
        self.buf += b
        return len(b)

    def flush(self) -> None:
        pass

    def take(self) -> bytes:
        out = bytes(self.buf)
        self.buf.clear()
        return out


def stream(entries: list[tuple[str, "Key | bytes | Callable[[], bytes]"]]):
    """Yield the zip of `entries` = [(name inside the zip, storage key — or bytes made on the fly, like a recap PDF,
    or a function that makes them when their turn comes, like a montage)] in chunks. Files are copied byte for byte
    (deflate is lossless): the lab gets the originals as uploaded."""
    sink = ZipSink()
    with zipfile.ZipFile(sink, "w", zipfile.ZIP_DEFLATED, compresslevel=1) as zf:
        for arcname, k in entries:
            if callable(k):
                k = k()                                    # one montage in memory at a time
            made = isinstance(k, (bytes, bytearray))
            info = zipfile.ZipInfo(arcname, date_time=time.localtime(time.time() if made else storage.stat(k).mtime)[:6])
            info.compress_type = zipfile.ZIP_DEFLATED
            with zf.open(info, "w") as entry:
                for chunk in ([bytes(k)] if made else storage.iter_chunks(k)):
                    entry.write(chunk)
                    if len(sink.buf) >= 256 * 1024:
                        yield sink.take()
            yield sink.take()
    yield sink.take()


def attachment(name: str) -> str:
    """Content-Disposition for a download: an ASCII fallback plus the real (UTF-8) name."""
    ascii_name = name.encode("ascii", "replace").decode().replace('"', "_").replace("?", "_")
    return f"attachment; filename=\"{ascii_name}\"; filename*=utf-8''{quote(name)}"
