from __future__ import annotations

import json
from typing import Any, Mapping


def _extract_text_from_result(result: Mapping[str, Any]) -> str:
    """
    Extract text from a result structure.

    Supports A2A patterns like:
    - result.artifacts[0].parts[0].text
    - result.status.message.parts[0].text
    """
    artifacts = result.get("artifacts")
    if isinstance(artifacts, list) and artifacts:
        parts = artifacts[0].get("parts") if isinstance(artifacts[0], dict) else None
        if isinstance(parts, list) and parts:
            text = parts[0].get("text") if isinstance(parts[0], dict) else None
            if isinstance(text, str):
                return text

    status = result.get("status")
    if isinstance(status, dict):
        message = status.get("message")
        if isinstance(message, dict):
            parts = message.get("parts")
            if isinstance(parts, list) and parts:
                text = parts[0].get("text") if isinstance(parts[0], dict) else None
                if isinstance(text, str):
                    return text

    return ""


def _parse_sse_events(raw_text: str) -> list[dict[str, Any]]:
    """Parse SSE text payload into JSON events."""
    normalized = raw_text.replace("\r\n", "\n")
    blocks = normalized.split("\n\n")
    events: list[dict[str, Any]] = []

    for block in blocks:
        if not block.strip():
            continue

        data_lines: list[str] = []
        for line in block.split("\n"):
            if line.startswith("data:"):
                payload = line[5:].strip()
                if payload:
                    data_lines.append(payload)

        if not data_lines:
            continue

        combined = "\n".join(data_lines).strip()
        if not combined or combined == "[DONE]":
            continue

        try:
            item = json.loads(combined)
            if isinstance(item, dict):
                events.append(item)
        except Exception:
            continue

    return events
