/** Evolution Dashboard API client */

import { BaseApiClient } from './base'

const API_BASE = '/api/v1'

export interface Experience {
  id: string
  task_type: string
  goal: string
  outcome: string
  duration: number
  created_at: string
  steps_summary?: string
  failure_reasons?: string[]
  optimization_tips?: string[]
}

export interface EvolutionMetrics {
  total_tasks: number
  success_rate: number
  avg_duration: number
  retry_rate: number
  experience_count: number
  period_start: string | null
  period_end: string
}

export interface TrendPoint {
  date: string
  success_rate: number
  avg_duration: number
  retry_rate: number
}

export interface PitfallWarning {
  step: string
  risk_level: 'high' | 'medium' | 'low'
  reason: string
  historical_failure_rate: number
  suggestion: string
}

export interface PathOptimization {
  id: string
  task_type: string
  previous_path: string[]
  current_path: string[]
  improvement: number
  updated_at: string | null
}

export interface UsageRecord {
  date: string
  provider: string
  model: string
  tokens: number
  requests: number
  errors: number
  avg_latency_ms: number
}

export interface UsageSummary {
  total_tokens: number
  total_requests: number
  success_rate: number
  avg_latency_ms: number
}

class EvolutionApiClient extends BaseApiClient {
  constructor(baseUrl: string = API_BASE) {
    super(baseUrl)
  }

  /** List recent experiences */
  async getExperiences(params?: {
    task_type?: string
    outcome?: string
    limit?: number
  }): Promise<{ experiences: Experience[]; total: number }> {
    const query = new URLSearchParams()
    if (params?.task_type) query.set('task_type', params.task_type)
    if (params?.outcome) query.set('outcome', params.outcome)
    if (params?.limit) query.set('limit', String(params.limit))
    const qs = query.toString()
    return this.request(`/evolution-dashboard/experiences${qs ? '?' + qs : ''}`)
  }

  /** Get evolution metrics */
  async getMetrics(period?: string): Promise<{
    metrics: EvolutionMetrics
    trends: TrendPoint[]
  }> {
    const query = new URLSearchParams()
    if (period) query.set('period', period)
    const qs = query.toString()
    return this.request(`/evolution-dashboard/metrics${qs ? '?' + qs : ''}`)
  }

  /** Check pitfall warnings */
  async checkPitfalls(params: {
    task_type: string
    steps: string[]
  }): Promise<{ warnings: PitfallWarning[] }> {
    const query = new URLSearchParams()
    query.set('task_type', params.task_type)
    if (params.steps.length > 0) {
      query.set('steps', params.steps.join(','))
    }
    return this.request(`/evolution-dashboard/pitfalls?${query.toString()}`)
  }

  /** Get path optimization history */
  async getPathOptimizations(params?: {
    task_type?: string
    limit?: number
  }): Promise<{ optimizations: PathOptimization[] }> {
    const query = new URLSearchParams()
    if (params?.task_type) query.set('task_type', params.task_type)
    if (params?.limit) query.set('limit', String(params.limit))
    const qs = query.toString()
    return this.request(`/evolution-dashboard/path-optimizations${qs ? '?' + qs : ''}`)
  }

  /** Get LLM usage statistics */
  async getUsage(params?: { period?: string }): Promise<{
    usage: UsageRecord[]
    summary: UsageSummary
  }> {
    const query = new URLSearchParams()
    if (params?.period) query.set('period', params.period)
    const qs = query.toString()
    return this.request(`/evolution-dashboard/usage${qs ? '?' + qs : ''}`)
  }

  /** Create a WebSocket connection for real-time updates */
  createWebSocket(): WebSocket {
    return super.createWebSocket('/evolution-dashboard/ws')
  }
}

export const evolutionApi = new EvolutionApiClient()
