"""REQ-FD-001: Extract MEDIA: tags from tool result strings."""

from __future__ import annotations

import re

_MEDIA_RE = re.compile(
    r'^MEDIA:'
    r'(?:"([^"]+)"'   # quoted path
    r'|(\S+))',        # unquoted path (no whitespace)
    re.MULTILINE,
)


def extract_media_from_tool_result(result: str) -> list[str]:
    """
    Parse ``MEDIA:<path>`` markers from a tool's return string.

    Supports:
    - ``MEDIA:/absolute/path``
    - ``MEDIA:relative/path``
    - ``MEDIA:"/path/with spaces/file.pdf"``
    - ``MEDIA:file:///url-style``
    - Multiple markers (one per line)
    """
    if not result or "MEDIA:" not in result:
        return []

    paths: list[str] = []
    for m in _MEDIA_RE.finditer(result):
        raw = m.group(1) or m.group(2) or ""
        raw = raw.strip()
        if raw.startswith("file://"):
            raw = raw[len("file://"):]
        if raw:
            paths.append(raw)
    return paths


def strip_media_tags(text: str) -> str:
    """Remove all ``MEDIA:`` lines from text (for user-facing output)."""
    return _MEDIA_RE.sub("", text).strip()
