/**
 * Agent progress tracking types — unified superset for desktop and mobile.
 *
 * Desktop‑only and mobile‑only fields are marked optional so both platforms
 * can consume the same interface without breaking.
 */

import type { ToolCall, ToolResult, ConversationHistoryMessage } from './types'
import type { AgentConversationState } from './conversation-state'

// ---------------------------------------------------------------------------
// ACP (Agent Communication Protocol) related types
// ---------------------------------------------------------------------------

/**
 * A message in a sub-agent conversation (desktop-specific, optional in shared).
 */
export interface ACPSubAgentMessage {
  /** Role of the sender */
  role: 'user' | 'assistant' | 'tool'
  /** Message content */
  content: string
  /** Structured tool calls when available */
  toolCalls?: ToolCall[]
  /** Structured tool results when available */
  toolResults?: ToolResult[]
  /** Tool name if this is a tool call/result */
  toolName?: string
  /** Tool input (for tool calls) */
  toolInput?: unknown
  /** Timestamp */
  timestamp: number
}

/**
 * Progress information for a delegated ACP sub-agent.
 */
export interface ACPDelegationProgress {
  /** Unique identifier for this delegation run */
  runId: string
  /** Name of the ACP agent being delegated to */
  agentName: string
  /** How this delegated run is connected/executed */
  connectionType?: 'internal' | 'acpx' | 'acp' | 'stdio' | 'remote'
  /** The task that was delegated */
  task: string
  /** Current status of the delegation */
  status: 'pending' | 'spawning' | 'running' | 'completed' | 'failed' | 'cancelled'
  /** Optional progress message from the sub-agent */
  progressMessage?: string
  /** When the delegation started */
  startTime: number
  /** When the delegation ended (if complete) */
  endTime?: number
  /** Result summary (if completed) */
  resultSummary?: string
  /** Error message (if failed) */
  error?: string
  /** Session ID for local ACP/stdio delegated sessions */
  acpSessionId?: string
  /** Internal DotAgents sub-session ID for internal delegations */
  subSessionId?: string
  /** DotAgents conversation ID for internal/stateful delegated sessions */
  conversationId?: string
  /** Remote ACP run ID for externally-managed async delegations */
  acpRunId?: string
  /** Full conversation history from the sub-agent */
  conversation?: ACPSubAgentMessage[]
}

/**
 * State of all active ACP delegations for a session.
 */
export interface ACPDelegationState {
  /** Session ID of the parent agent */
  parentSessionId: string
  /** All delegations for this session */
  delegations: ACPDelegationProgress[]
  /** Number of active (non-completed) delegations */
  activeCount: number
}

/**
 * Value option for an ACP configuration dropdown/choice.
 */
export interface ACPConfigOptionValue {
  value: string
  name: string
  description?: string
}

/**
 * A configurable option exposed by an ACP agent.
 */
export interface ACPConfigOption {
  id: string
  name: string
  description?: string
  category?: string
  type: string
  currentValue: string
  options: ACPConfigOptionValue[]
}

// ---------------------------------------------------------------------------
// Agent step summary (dual-model mode, desktop-specific)
// ---------------------------------------------------------------------------

/**
 * Agent step summary generated by a weak/summarization model.
 */
export interface AgentStepSummary {
  id: string
  sessionId: string
  stepNumber: number
  timestamp: number

  /** What the agent just did (single line) */
  actionSummary: string

  /**
   * Durable note candidates extracted from this step.
   * These should be reusable in future sessions (preferences, constraints,
   * decisions, facts, insights), NOT step-by-step telemetry.
   */
  noteCandidates?: string[]

  // --- Desktop-specific metadata ---
  importance?: 'low' | 'medium' | 'high' | 'critical'
  savedToKnowledgeNote?: boolean
  userNotes?: string
  tags?: string[]

  // Legacy fields (kept for backward compatibility)
  keyFindings?: string[]
  nextSteps?: string
  decisionsMade?: string[]
}

// ---------------------------------------------------------------------------
// AgentProgressStep — unified superset
// ---------------------------------------------------------------------------

/**
 * A single step in an agent's progress.
 *
 * The `type` field is the union of desktop and mobile step types.
 * The `status` field is the union of desktop and mobile status values.
 */
export interface AgentProgressStep {
  id: string
  type:
    | 'thinking'
    | 'tool_call'
    | 'tool_result'
    | 'completion'
    | 'tool_approval'
    // Mobile-specific types:
    | 'response'
    | 'error'
    | 'pending_approval'
  title: string
  description?: string
  status:
    | 'pending'
    | 'in_progress'
    | 'completed'
    | 'error'
    // Desktop-specific statuses:
    | 'awaiting_approval'
  timestamp: number

  // --- Shared fields ---
  llmContent?: string
  toolCall?: ToolCall
  toolResult?: ToolResult

  // --- Mobile-specific ---
  /** Raw content string (mobile uses this instead of llmContent in some cases) */
  content?: string

  // --- Desktop-specific ---
  approvalRequest?: {
    approvalId: string
    toolName: string
    arguments: any
  }
  /** If this step is a delegation to a sub-agent */
  delegation?: ACPDelegationProgress
  executionStats?: {
    durationMs?: number
    totalTokens?: number
    toolUseCount?: number
    inputTokens?: number
    outputTokens?: number
    cacheHitTokens?: number
  }
  subagentId?: string
}

/**
 * Ordered user-facing response emitted during a single agent run.
 * Consumers should use `id` for playback/delivery dedupe instead of raw text.
 */
export interface AgentUserResponseEvent {
  id: string
  sessionId: string
  runId?: number
  ordinal: number
  text: string
  timestamp: number
}

// ---------------------------------------------------------------------------
// AgentProgressUpdate — unified superset
// ---------------------------------------------------------------------------

/**
 * Full progress update for an agent session.
 *
 * All platform-specific fields are optional so that both desktop and mobile
 * can use this single type without breaking.
 */
export interface AgentProgressUpdate {
  sessionId: string
  /** Parent session ID when this update belongs to a delegated sub-agent/sub-session. */
  parentSessionId?: string
  conversationId?: string
  currentIteration: number
  maxIterations: number
  steps: AgentProgressStep[]
  isComplete: boolean

  // --- Shared fields ---
  conversationState?: AgentConversationState
  finalContent?: string
  /**
   * User-facing response set via respond_to_user tool.
   * On voice interfaces: spoken aloud via TTS.
   * On messaging channels (mobile, WhatsApp): sent as a message.
   * Consumers should fall back to finalContent if this is not set.
   */
  userResponse?: string
  /**
   * Ordered respond_to_user events for the current run.
   * Prefer this over `userResponse` / `userResponseHistory` when available.
   */
  responseEvents?: AgentUserResponseEvent[]
  conversationHistory?: ConversationHistoryMessage[]
  /** Total history size when `conversationHistory` is a lazy-loaded display window. */
  conversationHistoryTotalCount?: number
  /** Start index of `conversationHistory` within the full persisted history window. */
  conversationHistoryStartIndex?: number
  streamingContent?: {
    text: string
    isStreaming: boolean
  }

  // --- Mobile-specific ---
  /** @deprecated Use userResponse instead. Kept for backward compatibility with older backends. */
  spokenContent?: string

  // --- Desktop-specific ---
  /**
   * Monotonic run counter for a reused session ID.
   * Lets the renderer ignore stale updates from older runs.
   */
  runId?: number
  conversationTitle?: string
  isSnoozed?: boolean
  /**
   * History of past respond_to_user calls (excluding the current/latest one).
   * Shown as collapsed items in the UI with TTS playback support.
   */
  userResponseHistory?: string[]
  sessionStartIndex?: number
  pendingToolApproval?: {
    approvalId: string
    toolName: string
    arguments: any
  }
  retryInfo?: {
    isRetrying: boolean
    attempt: number
    maxAttempts?: number
    delaySeconds: number
    reason: string
    startedAt: number
  }
  contextInfo?: {
    estTokens: number
    maxTokens: number
  }
  modelInfo?: {
    provider: string
    model: string
  }
  /** Profile name associated with this session (from profile snapshot) */
  profileName?: string
  acpSessionInfo?: {
    agentName?: string
    agentTitle?: string
    agentVersion?: string
    currentModel?: string
    currentMode?: string
    availableModels?: Array<{ id: string; name: string; description?: string }>
    availableModes?: Array<{ id: string; name: string; description?: string }>
    configOptions?: ACPConfigOption[]
  }
  /** Dual-model summarization data */
  stepSummaries?: AgentStepSummary[]
  latestSummary?: AgentStepSummary
}

/**
 * Callback type for progress updates.
 */
export type OnProgressCallback = (update: AgentProgressUpdate) => void
