"""Structured IO for typed input/output - Phase 10.2"""

from dataclasses import dataclass
from typing import Any, Generic, TypeVar

T = TypeVar("T")


@dataclass
class StructuredInput:
    """Structured input wrapper"""

    skill_name: str
    parameters: dict[str, Any]
    metadata: dict[str, Any]


@dataclass
class StructuredOutput:
    """Structured output wrapper"""

    skill_name: str
    result: Any
    success: bool
    error: str | None = None
    metadata: dict[str, Any] | None = None


class StructuredIO:
    """Handles structured input/output for agent communication"""

    def parse_input(self, data: dict[str, Any]) -> StructuredInput:
        """Parse structured input from dictionary.

        Args:
            data: Dictionary containing skill_name, parameters, and metadata

        Returns:
            StructuredInput instance

        Raises:
            ValueError: If required fields are missing
        """
        if not isinstance(data, dict):
            raise ValueError("Input data must be a dictionary")

        skill_name = data.get("skill_name")
        if not skill_name:
            raise ValueError("Missing required field: skill_name")
        if not isinstance(skill_name, str):
            raise ValueError("skill_name must be a string")

        parameters = data.get("parameters")
        if parameters is None:
            raise ValueError("Missing required field: parameters")
        if not isinstance(parameters, dict):
            raise ValueError("parameters must be a dictionary")

        metadata = data.get("metadata", {})
        if not isinstance(metadata, dict):
            raise ValueError("metadata must be a dictionary")

        return StructuredInput(skill_name=skill_name, parameters=parameters, metadata=metadata)

    def format_output(self, output: StructuredOutput) -> dict[str, Any]:
        """Format structured output to dictionary.

        Args:
            output: StructuredOutput instance

        Returns:
            Dictionary representation of the output
        """
        result = {
            "skill_name": output.skill_name,
            "result": output.result,
            "success": output.success,
        }

        if output.error is not None:
            result["error"] = output.error

        if output.metadata is not None:
            result["metadata"] = output.metadata

        return result
