"""Response format validation rules."""

from __future__ import annotations

from typing import Any

from hatchdx.validator.models import ValidationResult, ValidationRule
from hatchdx.validator.registry import register_rule


@register_rule(
    name="dual_format_support",
    category="response",
    severity="info",
    description="Tools should support dual format responses (JSON + Markdown) for richer client UX.",
)
def check_dual_format_support(
    tools: list[Any],
    *,
    call_results: dict[str, Any] | None = None,
    **kwargs: Any,
) -> list[ValidationResult]:
    """Check whether tool responses include both structured and human-readable content.

    ``call_results`` maps tool names to ``ToolCallResult`` objects from
    successful calls.  If not provided, the check reports a suggestion
    based on tool definitions alone.
    """
    rule: ValidationRule = check_dual_format_support._rule  # type: ignore[attr-defined]
    results: list[ValidationResult] = []

    if call_results is None:
        # Static check only — give a general suggestion.
        for tool in tools:
            results.append(ValidationResult(
                rule=rule,
                passed=True,
                message=(
                    f"Tool '{tool.name}': consider returning both JSON and Markdown "
                    f"content types for richer client rendering."
                ),
                tool_name=tool.name,
            ))
        return results

    for tool_name, call_result in call_results.items():
        content = call_result.content
        content_types = {item.get("type") for item in content if isinstance(item, dict)}

        has_text = "text" in content_types
        has_resource = "resource" in content_types or "image" in content_types

        if has_text and has_resource:
            results.append(ValidationResult(
                rule=rule,
                passed=True,
                message=f"Tool '{tool_name}' returns multiple content types.",
                tool_name=tool_name,
            ))
        elif has_text:
            results.append(ValidationResult(
                rule=rule,
                passed=False,
                message=(
                    f"Tool '{tool_name}' only returns text content. "
                    f"Consider adding structured (resource/image) content for richer UX."
                ),
                tool_name=tool_name,
            ))
        else:
            results.append(ValidationResult(
                rule=rule,
                passed=False,
                message=(
                    f"Tool '{tool_name}' does not return text content. "
                    f"Consider adding human-readable text alongside structured data."
                ),
                tool_name=tool_name,
            ))

    return results
