"""Inbound media download helpers."""

from __future__ import annotations

import mimetypes
from dataclasses import dataclass

import httpx

from asedclaw.media.mime import detect_mime
from asedclaw.media.store import MediaStore
from loguru import logger


@dataclass
class DownloadedMedia:
    """Normalized result of downloading a remote attachment."""

    path: str
    size: int
    mime_type: str


async def download_to_media_store(
    url: str,
    store: MediaStore,
    *,
    filename: str | None = None,
    timeout_s: float = 20.0,
    max_bytes: int = 10 * 1024 * 1024,
    headers: dict[str, str] | None = None,
) -> DownloadedMedia:
    """Download a remote file into the local media store."""
    async with httpx.AsyncClient(timeout=timeout_s, follow_redirects=True) as client:
        response = await client.get(url, headers=headers)
        response.raise_for_status()
        data = response.content

    if len(data) > max_bytes:
        raise ValueError(f"inbound attachment exceeds {max_bytes} bytes")

    suffix = ""
    if filename:
        suffix = mimetypes.guess_extension(mimetypes.guess_type(filename)[0] or "", strict=False) or ""
    saved = store.save_bytes(data, suffix=suffix, original_filename=filename)
    logger.info("ASED inbound attachment saved: {}", saved)
    mime_type, _ = detect_mime(saved)
    return DownloadedMedia(path=str(saved), size=len(data), mime_type=mime_type)
