/**
 * Agent Loop — 内部类型定义
 *
 * 用于 Agent Loop 引擎内部的状态管理和迭代记录。
 */

import type { MetonaToolCall, MetonaToolResult } from '../types';

// ===== Agent Loop 状态机 =====

export enum AgentLoopState {
  INIT = 'INIT',
  THINKING = 'THINKING',
  PARSING = 'PARSING',
  EXECUTING = 'EXECUTING',
  OBSERVING = 'OBSERVING',
  REFLECTING = 'REFLECTING',
  COMPRESSING = 'COMPRESSING',
  TERMINATED = 'TERMINATED',
}

export enum TerminationReason {
  COMPLETED = 'completed',
  MAX_ITERATIONS = 'max_iterations',
  TIMEOUT = 'timeout',
  USER_INTERRUPT = 'user_interrupt',
  ERROR = 'error',
  /** v0.3.0: 检测到死循环（连续3轮相同工具调用） */
  DEAD_LOOP = 'dead_loop',
}

// ===== 迭代步骤 =====

export interface Thought {
  id: string;
  content: string;
  reasoningContent?: string;
  timestamp: number;
  iteration: number;
}

export interface IterationStep {
  iteration: number;
  state: AgentLoopState;
  startedAt: number;
  completedAt?: number;
  thought?: Thought;
  toolCalls?: MetonaToolCall[];
  toolResults?: MetonaToolResult[];
  tokenUsage?: TokenUsage;
}

export interface TokenUsage {
  promptTokens: number;
  completionTokens: number;
  totalTokens: number;
}

// ===== Agent Loop 配置 =====

export interface AgentLoopConfig {
  maxIterations: number;
  timeoutMs: number;
  totalTimeoutMs: number;
  enableReflection: boolean;
  compressionThreshold: number;
  contextWindow: number;
  retryCount: number;
  temperature: number;
  /** 最大生成 token 数（默认 63488） */
  maxTokens: number;
  /** 是否启用思考模式（默认 true） */
  thinkingEnabled: boolean;
  /** 思考强度（默认 'high'） */
  thinkingEffort: 'low' | 'medium' | 'high' | 'max';
  /** Ollama 上下文窗口大小（num_ctx），其他 Provider 忽略 */
  contextLength?: number;
  /** 工具执行兜底超时（ms，默认 120000），实际取 max(此值, tool.timeoutMs) */
  toolExecutionTimeoutMs?: number;
}

// ===== Agent Loop 输出 =====

export interface AgentLoopOutput {
  finalAnswer: string;
  terminationReason: TerminationReason;
  iterations: IterationStep[];
  totalTokenUsage: TokenUsage;
  durationMs: number;
  metadata: Record<string, unknown>;
}
