"""REQ-FD-002: Path security whitelist for media delivery."""

from __future__ import annotations

from pathlib import Path

TRUSTED_MEDIA_TOOLS: set[str] = {
    "exec",
    "write_file",
    "edit_file",
    "web_fetch",
    "message",
}


def validate_media_path(
    path: str,
    workspace: Path | None = None,
    extra_allowed_dirs: list[str] | None = None,
) -> bool:
    """
    Check whether *path* is safe to deliver.

    Allowed:
    - HTTP/HTTPS URLs
    - Paths inside *workspace*
    - Paths inside ``~/.asedclaw/media/``
    - Paths inside any *extra_allowed_dirs*
    """
    stripped = path.strip()
    if not stripped:
        return False

    if stripped.lower().startswith(("http://", "https://")):
        return True

    try:
        resolved = Path(stripped).expanduser().resolve()
    except Exception:
        return False

    allowed_roots: list[Path] = []
    if workspace is not None:
        allowed_roots.append(workspace.resolve())
    media_dir = (Path.home() / ".asedclaw" / "media").resolve()
    allowed_roots.append(media_dir)
    if extra_allowed_dirs:
        for d in extra_allowed_dirs:
            try:
                allowed_roots.append(Path(d).expanduser().resolve())
            except Exception:
                continue

    for allowed in allowed_roots:
        try:
            resolved.relative_to(allowed)
            return True
        except ValueError:
            pass

    return False
