/** Evolution Dashboard API client */

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
}

class EvolutionApiClient {
  private baseUrl: string

  constructor(baseUrl: string = API_BASE) {
    this.baseUrl = baseUrl
  }

  private async request<T>(path: string, options: RequestInit = {}): Promise<T> {
    const url = `${this.baseUrl}${path}`
    const headers: HeadersInit = {
      'Content-Type': 'application/json',
      ...options.headers,
    }
    const response = await fetch(url, { ...options, headers })

    if (!response.ok) {
      const error: { status: number; message: string; detail?: string } = {
        status: response.status,
        message: response.statusText,
      }
      try {
        const body = await response.json()
        error.detail = body.detail ?? body.message
        error.message = error.detail ?? error.message
      } catch {
        // response body is not JSON
      }
      throw error
    }

    return response.json() as Promise<T>
  }

  /** 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 : ''}`)
  }

  /** Create a WebSocket connection for real-time updates */
  createWebSocket(): WebSocket {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    const host = window.location.host
    return new WebSocket(`${protocol}//${host}${this.baseUrl}/evolution-dashboard/ws`)
  }
}

export const evolutionApi = new EvolutionApiClient()
