"""Data models for the agent subsystem."""

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Any

from thryve.core.context.models import ToolCall, ToolResult


# ---------------------------------------------------------------------------
# Enums
# ---------------------------------------------------------------------------

class StopReason(str, Enum):
    """Why an agent loop terminated."""

    COMPLETED = "completed"          # LLM returned text with no tool calls
    MAX_TURNS = "max_turns"          # Hit the turn limit
    LOOP_DETECTED = "loop_detected"  # Repeated identical tool calls
    REPEATED_TOOL = "repeated_tool"  # Same tool+args seen twice
    ERROR = "error"                  # Unrecoverable error


# ---------------------------------------------------------------------------
# Step & Turn
# ---------------------------------------------------------------------------

@dataclass
class StepOutput:
    """The output of a single step (one LLM call + tool execution round)."""

    turn: int
    tool_calls: list[ToolCall] = field(default_factory=list)
    tool_results: list[ToolResult] = field(default_factory=list)
    llm_text: str = ""
    metadata: dict[str, Any] = field(default_factory=dict)


@dataclass
class TurnResult:
    """The final result returned by an agent loop."""

    final_response: str
    steps: list[StepOutput] = field(default_factory=list)
    stop_reason: StopReason = StopReason.COMPLETED
    metadata: dict[str, Any] = field(default_factory=dict)


# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------

@dataclass
class LoopConfig:
    """Runtime configuration for :class:`AgentLoop`."""

    max_turns: int = 10
    max_steps_per_turn: int = 5
    loop_detection_window: int = 3  # consecutive identical-tool-call steps
    enable_auto_continue: bool = True
