/** Skills API client */

const API_BASE = '/api/v1/skill-management'

export interface ISkillInfo {
  name: string
  version: string
  description: string
  capabilities: string[]
  dependencies: string[]
  status: string
}

export interface ISkillDetail {
  name: string
  version: string
  description: string
  capabilities: string[]
  dependencies: string[]
  config: Record<string, unknown>
  health_status: string
}

export interface ICapabilityInfo {
  name: string
  display_name: string
  skill_count: number
}

export interface ISkillListResponse {
  skills: ISkillInfo[]
  total: number
  page: number
  size: number
}

async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
  const url = `${API_BASE}${path}`
  const headers: HeadersInit = {
    'Content-Type': 'application/json',
    ...options.headers,
  }

  const response = await fetch(url, { ...options, headers })

  if (!response.ok) {
    const error = { status: response.status, message: response.statusText }
    try {
      const body = await response.json()
      error.message = body.detail ?? body.message ?? error.message
    } catch {
      // use status text
    }
    throw error
  }

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

/** List all skills with optional filtering */
export async function listSkills(
  capability?: string,
  page: number = 1,
  size: number = 20
): Promise<ISkillListResponse> {
  const params = new URLSearchParams()
  if (capability) params.set('capability', capability)
  params.set('page', String(page))
  params.set('size', String(size))
  return request<ISkillListResponse>(`/skills?${params.toString()}`)
}

/** Get skill detail */
export async function getSkillDetail(skillName: string): Promise<ISkillDetail> {
  return request<ISkillDetail>(`/skills/${encodeURIComponent(skillName)}`)
}

/** Check skill health */
export async function checkSkillHealth(
  skillName: string
): Promise<{ skill_name: string; status: string; message: string }> {
  return request(`/skills/${encodeURIComponent(skillName)}/health`)
}

/** List all capability tags */
export async function listCapabilities(): Promise<{ capabilities: ICapabilityInfo[] }> {
  return request<{ capabilities: ICapabilityInfo[] }>('/capabilities')
}

/** Reload a skill */
export async function reloadSkill(
  skillName: string
): Promise<{ skill_name: string; status: string; message: string }> {
  return request(`/skills/${encodeURIComponent(skillName)}/reload`, {
    method: 'POST',
  })
}
