import { api } from './client'

export interface Agent {
  id: string
  name: string
  description: string
  current_version: number
  status: string
  tags: string[]
  config: Record<string, unknown>
  agent_dir: string
  work_dir: string
  source_dir: string
  run_dir: string
  kb_ids: string[]
  kb_search_mode: string
  /** 创建来源的内置包 id（如 teaching.exam-builder），手建智能体为空 */
  agent_template?: string
  created_at: string
  updated_at: string
}

export interface AgentKnowledge {
  kb_ids: string[]
  kb_search_mode: string
  knowledge_bases: Array<{
    id: string
    name: string
    root_dir: string
    description: string
  }>
}

export interface Run {
  id: string
  agent_id: string
  status: string
  input: string
  output: string
  duration_ms: number
  input_tokens: number
  output_tokens: number
  cache_read_tokens: number
  cache_creation_tokens: number
  cost_usd: number | null
  steps: number
  workspace_path: string | null
  error: string | null
  created_at: string
}

export interface WorkspaceFile {
  name: string
  path: string   // relative to workspace root
  size: number
  modified: number
}

export interface MemoryEntry {
  key: string
  content: string
  tier: string   // working | episodic | semantic
  tags: string[]
  source: string
  created_at: number
  expires_at: number
  access_count: number
}

// Persistent Memory (Letta 3-layer)
export type CoreMemory = Record<string, unknown>

export interface RecallEntry {
  run_id: string
  input: string
  output: string
  ts: string
}

export const agentsApi = {
  list: () => api.get<{ agents: Agent[] }>('/agents'),
  get: (id: string) => api.get<Agent>(`/agents/${id}`),
  // 会话记忆 thread
  threads: (agentId: string) =>
    api.get<{ threads: { id: string; title: string; run_count: number; updated_at: string }[] }>(
      `/agents/${agentId}/threads`),
  threadRuns: (agentId: string, threadId: string) =>
    api.get<{ runs: { id: string; input: string; output: string; status: string; workspace_path: string; created_at: string }[] }>(
      `/agents/${agentId}/threads/${threadId}/runs`),
  archiveThread: (agentId: string, threadId: string) =>
    api.post<{ ok: boolean }>(`/agents/${agentId}/threads/${threadId}/archive`),
  create: (body: {
    name: string
    description: string
    config: Record<string, unknown>
    tags: string[]
    agent_dir?: string
    work_dir?: string
    source_dir?: string
    run_dir?: string
    kb_ids?: string[]
    kb_search_mode?: string
  }) => api.post<{ agent_id: string }>('/agents', body),
  update: (id: string, body: {
    config: Record<string, unknown>
    agent_dir?: string
    work_dir?: string
    source_dir?: string
    run_dir?: string
    changelog?: string
    kb_ids?: string[]
    kb_search_mode?: string
  }) => api.put(`/agents/${id}`, body),
  delete: (id: string) => api.delete(`/agents/${id}`),
  runs: (id: string, limit = 50) =>
    api.get<{ runs: Run[] }>(`/agents/${id}/runs?limit=${limit}`),

  // Sub-agent (multi-agent orchestrator) config file
  subAgentConfig: (agentId: string, subName: string) =>
    api.get<{
      sub_name: string
      tool?: string
      path: string | null
      rel_path?: string
      inline: boolean
      content: string
    }>(`/agents/${agentId}/subagents/${encodeURIComponent(subName)}/config`),

  // Workspace file browsing
  workspaceFiles: (agentId: string, runId: string) =>
    api.get<{ files: WorkspaceFile[]; workspace_path: string }>(
      `/agents/${agentId}/runs/${runId}/workspace`
    ),
  workspaceDownloadUrl: (agentId: string, runId: string, filePath: string) =>
    `/api/v1/agents/${agentId}/runs/${runId}/workspace/${filePath}`,

  // Legacy memory management (tier-based MemoryService)
  memory: (agentId: string) =>
    api.get<{ entries: MemoryEntry[]; count: number }>(`/agents/${agentId}/memory`),
  deleteMemory: (agentId: string, key: string) =>
    api.delete(`/agents/${agentId}/memory/${key}`),

  // Persistent Memory — Layer 1: Core Memory
  coreMemory: (agentId: string) =>
    api.get<{ core: CoreMemory; agent_dir: string }>(`/agents/${agentId}/memory/core`),
  updateCoreMemory: (agentId: string, core: CoreMemory) =>
    api.put<{ core: CoreMemory }>(`/agents/${agentId}/memory/core`, core),
  clearCoreMemory: (agentId: string) =>
    api.delete<{ cleared: boolean }>(`/agents/${agentId}/memory/core`),

  // Persistent Memory — L2 自动提炼候选（待确认才转正）
  memoryCandidates: (agentId: string) =>
    api.get<{ candidates: { fact: string; confidence: number; created_at: string }[]; confirmed_facts: string[] }>(
      `/agents/${agentId}/memory/candidates`),
  confirmCandidate: (agentId: string, fact: string) =>
    api.post<{ ok: boolean }>(`/agents/${agentId}/memory/candidates/confirm`, { fact }),
  rejectCandidate: (agentId: string, fact: string) =>
    api.post<{ ok: boolean }>(`/agents/${agentId}/memory/candidates/reject`, { fact }),

  // Persistent Memory — Layer 2: Recall Log
  recallMemory: (agentId: string, n = 20) =>
    api.get<{ entries: RecallEntry[]; total: number }>(`/agents/${agentId}/memory/recall?n=${n}`),

  // Agent-KB linking
  getKBs: (agentId: string) =>
    api.get<AgentKnowledge>(`/agents/${agentId}/knowledge`),
  updateKBs: (agentId: string, kb_ids: string[], kb_search_mode: string) =>
    api.put<{ kb_ids: string[]; kb_search_mode: string }>(
      `/agents/${agentId}/knowledge`, { kb_ids, kb_search_mode }
    ),
}
