"""REQ-FD-003 / REQ-FD-005: Media staging with TTL-based cleanup."""

from __future__ import annotations

import shutil
import time
import uuid
from pathlib import Path
import mimetypes

from loguru import logger
from asedclaw.utils.helpers import safe_filename


class MediaStore:
    """Local file staging area with automatic TTL cleanup."""

    def __init__(self, base_dir: Path | None = None, ttl_seconds: int = 300):
        self._base = (base_dir or Path.home() / ".asedclaw" / "media").resolve()
        self._staged = self._base / "staged"
        self._staged.mkdir(parents=True, exist_ok=True)
        self.ttl_seconds = ttl_seconds

    @property
    def staged_dir(self) -> Path:
        return self._staged

    def save(self, source_path: str | Path, *, move: bool = False) -> Path:
        """Copy (or move) a file into the staging area. Returns the staged path."""
        src = Path(source_path).resolve()
        suffix = src.suffix or ""
        dst = self._staged / f"{uuid.uuid4().hex}{suffix}"
        if move:
            shutil.move(str(src), str(dst))
        else:
            shutil.copy2(str(src), str(dst))
        return dst

    def save_bytes(self, data: bytes, suffix: str = "", original_filename: str | None = None) -> Path:
        """Write raw bytes into the staging area. Returns the staged path."""
        if original_filename:
            safe_name = safe_filename(Path(original_filename).name)
            if safe_name:
                chosen_suffix = Path(safe_name).suffix or suffix
                if not chosen_suffix:
                    guessed = mimetypes.guess_extension("application/octet-stream")
                    if guessed:
                        chosen_suffix = guessed
                stem = Path(safe_name).stem or "attachment"
                dst = self._staged / f"{stem}---{uuid.uuid4().hex}{chosen_suffix}"
            else:
                dst = self._staged / f"{uuid.uuid4().hex}{suffix}"
        else:
            dst = self._staged / f"{uuid.uuid4().hex}{suffix}"
        dst.write_bytes(data)
        return dst

    def cleanup(self, max_age_seconds: int | None = None) -> int:
        """Remove staged files older than *max_age_seconds* (defaults to TTL). Returns count removed."""
        ttl = max_age_seconds if max_age_seconds is not None else self.ttl_seconds
        cutoff = time.time() - ttl
        removed = 0
        try:
            for f in self._staged.iterdir():
                if f.is_file() and f.stat().st_mtime < cutoff:
                    f.unlink(missing_ok=True)
                    removed += 1
        except Exception:
            logger.debug("MediaStore cleanup error (non-fatal)")
        return removed
