from __future__ import annotations

from collections.abc import Mapping
from typing import Any, TypeVar, BinaryIO, TextIO, TYPE_CHECKING, Generator

from attrs import define as _attrs_define
from attrs import field as _attrs_field

from ..types import UNSET, Unset

from ..types import UNSET, Unset
from typing import cast
from typing import Literal, cast

if TYPE_CHECKING:
  from ..models.agent_step_event_detail_type_0_item import AgentStepEventDetailType0Item
  from ..models.step_usage import StepUsage
  from ..models.token_budget_context import TokenBudgetContext





T = TypeVar("T", bound="AgentStepEvent")



@_attrs_define
class AgentStepEvent:
    r""" A single agent step with a sequential index.

    Tool call steps have a detail list; lifecycle steps have a step string.
    The focus field carries the agent's current focus: what it's zeroing in on.
    The content field carries extended text (e.g. the research plan).

    Examples:
        {"type": "arbi.agent_step", "index": 1, "step": "planning",
         "content": "1. Search for force majeure clauses across all three contracts\n2. Compare scope and exclusions"}
        {"type": "arbi.agent_step", "index": 2,
         "focus": "Searching for force majeure clauses across the selected contracts.",
         "detail": [
            {"tool": "search_inside_documents", "query": "force majeure", "search_mode": "hybrid"},
            {"tool": "get_table_of_contents", "doc_ext_id": "doc-abc12345"}
        ]}
        {"type": "arbi.agent_step", "index": 3,
         "focus": "Comparing the provisions found in Contract A with Contract B.",
         "detail": [
            {"tool": "read_document", "doc_ext_id": "doc-abc12345", "range_count": 2, "digest": false}
        ]}
        {"type": "arbi.agent_step", "index": 3, "detail": [
            {"tool": "web_search", "query": "latest arbitration developments 2026"}
        ]}
        {"type": "arbi.agent_step", "index": 3, "detail": [
            {"tool": "personal_agent", "task": "Execute Python code to compute the SHA256 hash..."}
        ]}
        {"type": "arbi.agent_step", "index": 3, "detail": [
            {"tool": "read_url", "url": "https://example.com/article"}
        ]}
        {"type": "arbi.agent_step", "index": 4, "step": "evaluation", "detail": [
            {"statement": "Newton prosecuted 28 coiners", "chunk_ids": ["chunk-abc"]},
            {"statement": "Counterfeiting was high treason", "chunk_ids": ["chunk-def"]}
        ]}
        {"type": "arbi.agent_step", "index": 5, "step": "tool_progress", "detail": [
            {"tool": "read_url", "message": "Fetching page"}
        ]}
        {"type": "arbi.agent_step", "index": 6, "step": "answering"}
        {"type": "arbi.agent_step", "index": 7, "step": "reviewing"}

        Attributes:
            index (int): Sequential step number (1-based)
            t (float | None | Unset): Seconds elapsed since stream start.
            type_ (Literal['arbi.agent_step'] | Unset):  Default: 'arbi.agent_step'.
            step (None | str | Unset): Lifecycle step (planning, answering, reviewing). Absent for tool calls.
            label (None | str | Unset): Display label for the step. Backend-driven, no frontend mapping needed.
            icon (None | str | Unset): Lucide icon name for the step (e.g. 'search'). Backend-driven, no frontend mapping
                needed.
            focus (None | str | Unset): Agent's current focus (single sentence). Present on tool call steps.
            content (None | str | Unset): Extended text content (e.g. research plan). Present on planning step.
            detail (list[AgentStepEventDetailType0Item] | None | Unset): Tool calls list. Each entry has 'tool' key plus
                tool-specific params.
            usage (None | StepUsage | Unset): Token usage for the LLM call in this step.
            total_tokens (int | None | Unset): Cumulative total tokens across all steps in the agent loop.
            step_tokens (int | None | Unset): Per-step token cost (input + output + reasoning) for the LLM call that
                produced this step.
            context (None | TokenBudgetContext | Unset): Token budget context snapshot. Present when retrieval counts
                change.
            outcome (None | str | Unset): Tool execution outcome (e.g. '15 chunks retrieved'). Sent as a follow-up event
                with the same index after tool execution.
            model_recommendation (None | str | Unset): Model tier recommended by FilterPlan in auto mode: 'fast', 'wise', or
                'premium'. Present only on the goal step when auto mode is active.
            selected_model (None | str | Unset): Actual model name selected after resolving the recommendation. Present only
                on the goal step when auto mode is active.
     """

    index: int
    t: float | None | Unset = UNSET
    type_: Literal['arbi.agent_step'] | Unset = 'arbi.agent_step'
    step: None | str | Unset = UNSET
    label: None | str | Unset = UNSET
    icon: None | str | Unset = UNSET
    focus: None | str | Unset = UNSET
    content: None | str | Unset = UNSET
    detail: list[AgentStepEventDetailType0Item] | None | Unset = UNSET
    usage: None | StepUsage | Unset = UNSET
    total_tokens: int | None | Unset = UNSET
    step_tokens: int | None | Unset = UNSET
    context: None | TokenBudgetContext | Unset = UNSET
    outcome: None | str | Unset = UNSET
    model_recommendation: None | str | Unset = UNSET
    selected_model: None | str | Unset = UNSET
    additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)





    def to_dict(self) -> dict[str, Any]:
        from ..models.agent_step_event_detail_type_0_item import AgentStepEventDetailType0Item
        from ..models.token_budget_context import TokenBudgetContext
        from ..models.step_usage import StepUsage
        index = self.index

        t: float | None | Unset
        if isinstance(self.t, Unset):
            t = UNSET
        else:
            t = self.t

        type_ = self.type_

        step: None | str | Unset
        if isinstance(self.step, Unset):
            step = UNSET
        else:
            step = self.step

        label: None | str | Unset
        if isinstance(self.label, Unset):
            label = UNSET
        else:
            label = self.label

        icon: None | str | Unset
        if isinstance(self.icon, Unset):
            icon = UNSET
        else:
            icon = self.icon

        focus: None | str | Unset
        if isinstance(self.focus, Unset):
            focus = UNSET
        else:
            focus = self.focus

        content: None | str | Unset
        if isinstance(self.content, Unset):
            content = UNSET
        else:
            content = self.content

        detail: list[dict[str, Any]] | None | Unset
        if isinstance(self.detail, Unset):
            detail = UNSET
        elif isinstance(self.detail, list):
            detail = []
            for detail_type_0_item_data in self.detail:
                detail_type_0_item = detail_type_0_item_data.to_dict()
                detail.append(detail_type_0_item)


        else:
            detail = self.detail

        usage: dict[str, Any] | None | Unset
        if isinstance(self.usage, Unset):
            usage = UNSET
        elif isinstance(self.usage, StepUsage):
            usage = self.usage.to_dict()
        else:
            usage = self.usage

        total_tokens: int | None | Unset
        if isinstance(self.total_tokens, Unset):
            total_tokens = UNSET
        else:
            total_tokens = self.total_tokens

        step_tokens: int | None | Unset
        if isinstance(self.step_tokens, Unset):
            step_tokens = UNSET
        else:
            step_tokens = self.step_tokens

        context: dict[str, Any] | None | Unset
        if isinstance(self.context, Unset):
            context = UNSET
        elif isinstance(self.context, TokenBudgetContext):
            context = self.context.to_dict()
        else:
            context = self.context

        outcome: None | str | Unset
        if isinstance(self.outcome, Unset):
            outcome = UNSET
        else:
            outcome = self.outcome

        model_recommendation: None | str | Unset
        if isinstance(self.model_recommendation, Unset):
            model_recommendation = UNSET
        else:
            model_recommendation = self.model_recommendation

        selected_model: None | str | Unset
        if isinstance(self.selected_model, Unset):
            selected_model = UNSET
        else:
            selected_model = self.selected_model


        field_dict: dict[str, Any] = {}
        field_dict.update(self.additional_properties)
        field_dict.update({
            "index": index,
        })
        if t is not UNSET:
            field_dict["t"] = t
        if type_ is not UNSET:
            field_dict["type"] = type_
        if step is not UNSET:
            field_dict["step"] = step
        if label is not UNSET:
            field_dict["label"] = label
        if icon is not UNSET:
            field_dict["icon"] = icon
        if focus is not UNSET:
            field_dict["focus"] = focus
        if content is not UNSET:
            field_dict["content"] = content
        if detail is not UNSET:
            field_dict["detail"] = detail
        if usage is not UNSET:
            field_dict["usage"] = usage
        if total_tokens is not UNSET:
            field_dict["total_tokens"] = total_tokens
        if step_tokens is not UNSET:
            field_dict["step_tokens"] = step_tokens
        if context is not UNSET:
            field_dict["context"] = context
        if outcome is not UNSET:
            field_dict["outcome"] = outcome
        if model_recommendation is not UNSET:
            field_dict["model_recommendation"] = model_recommendation
        if selected_model is not UNSET:
            field_dict["selected_model"] = selected_model

        return field_dict



    @classmethod
    def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
        from ..models.agent_step_event_detail_type_0_item import AgentStepEventDetailType0Item
        from ..models.step_usage import StepUsage
        from ..models.token_budget_context import TokenBudgetContext
        d = dict(src_dict)
        index = d.pop("index")

        def _parse_t(data: object) -> float | None | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            return cast(float | None | Unset, data)

        t = _parse_t(d.pop("t", UNSET))


        type_ = cast(Literal['arbi.agent_step'] | Unset , d.pop("type", UNSET))
        if type_ != 'arbi.agent_step'and not isinstance(type_, Unset):
            raise ValueError(f"type must match const 'arbi.agent_step', got '{type_}'")

        def _parse_step(data: object) -> None | str | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            return cast(None | str | Unset, data)

        step = _parse_step(d.pop("step", UNSET))


        def _parse_label(data: object) -> None | str | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            return cast(None | str | Unset, data)

        label = _parse_label(d.pop("label", UNSET))


        def _parse_icon(data: object) -> None | str | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            return cast(None | str | Unset, data)

        icon = _parse_icon(d.pop("icon", UNSET))


        def _parse_focus(data: object) -> None | str | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            return cast(None | str | Unset, data)

        focus = _parse_focus(d.pop("focus", UNSET))


        def _parse_content(data: object) -> None | str | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            return cast(None | str | Unset, data)

        content = _parse_content(d.pop("content", UNSET))


        def _parse_detail(data: object) -> list[AgentStepEventDetailType0Item] | None | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            try:
                if not isinstance(data, list):
                    raise TypeError()
                detail_type_0 = []
                _detail_type_0 = data
                for detail_type_0_item_data in (_detail_type_0):
                    detail_type_0_item = AgentStepEventDetailType0Item.from_dict(detail_type_0_item_data)



                    detail_type_0.append(detail_type_0_item)

                return detail_type_0
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            return cast(list[AgentStepEventDetailType0Item] | None | Unset, data)

        detail = _parse_detail(d.pop("detail", UNSET))


        def _parse_usage(data: object) -> None | StepUsage | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            try:
                if not isinstance(data, dict):
                    raise TypeError()
                usage_type_0 = StepUsage.from_dict(data)



                return usage_type_0
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            return cast(None | StepUsage | Unset, data)

        usage = _parse_usage(d.pop("usage", UNSET))


        def _parse_total_tokens(data: object) -> int | None | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            return cast(int | None | Unset, data)

        total_tokens = _parse_total_tokens(d.pop("total_tokens", UNSET))


        def _parse_step_tokens(data: object) -> int | None | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            return cast(int | None | Unset, data)

        step_tokens = _parse_step_tokens(d.pop("step_tokens", UNSET))


        def _parse_context(data: object) -> None | TokenBudgetContext | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            try:
                if not isinstance(data, dict):
                    raise TypeError()
                context_type_0 = TokenBudgetContext.from_dict(data)



                return context_type_0
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            return cast(None | TokenBudgetContext | Unset, data)

        context = _parse_context(d.pop("context", UNSET))


        def _parse_outcome(data: object) -> None | str | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            return cast(None | str | Unset, data)

        outcome = _parse_outcome(d.pop("outcome", UNSET))


        def _parse_model_recommendation(data: object) -> None | str | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            return cast(None | str | Unset, data)

        model_recommendation = _parse_model_recommendation(d.pop("model_recommendation", UNSET))


        def _parse_selected_model(data: object) -> None | str | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            return cast(None | str | Unset, data)

        selected_model = _parse_selected_model(d.pop("selected_model", UNSET))


        agent_step_event = cls(
            index=index,
            t=t,
            type_=type_,
            step=step,
            label=label,
            icon=icon,
            focus=focus,
            content=content,
            detail=detail,
            usage=usage,
            total_tokens=total_tokens,
            step_tokens=step_tokens,
            context=context,
            outcome=outcome,
            model_recommendation=model_recommendation,
            selected_model=selected_model,
        )


        agent_step_event.additional_properties = d
        return agent_step_event

    @property
    def additional_keys(self) -> list[str]:
        return list(self.additional_properties.keys())

    def __getitem__(self, key: str) -> Any:
        return self.additional_properties[key]

    def __setitem__(self, key: str, value: Any) -> None:
        self.additional_properties[key] = value

    def __delitem__(self, key: str) -> None:
        del self.additional_properties[key]

    def __contains__(self, key: str) -> bool:
        return key in self.additional_properties
