/**
 * Extraction Service API client for the admin dashboard.
 * Uses @bytelyst/api-client shared package.
 *
 * Provides typed methods for transcript extraction, task management,
 * and sidecar health checks.
 */

import { createApiClient } from '@bytelyst/api-client';

const extractionApi = createApiClient({
  baseUrl: `${process.env.EXTRACTION_SERVICE_URL || 'http://localhost:4005'}/api`,
});

// ── Types ────────────────────────────────────────────────────────

export interface ExtractionEntity {
  extraction_class: string;
  extraction_text: string;
  attributes?: Record<string, string>;
  start_offset?: number;
  end_offset?: number;
}

export interface ExtractResponse {
  extractions: ExtractionEntity[];
  metadata: {
    modelId: string;
    durationMs: number;
    tokenCount?: number;
    charCount: number;
  };
  requestId?: string;
}

export interface ExtractionTask {
  id: string;
  name: string;
  description?: string;
  prompt: string;
  classes: string[];
  builtIn: boolean;
  productId: string;
}

// ── Extract ──────────────────────────────────────────────────────

export async function extractText(
  text: string,
  taskId?: string,
  modelId?: string
): Promise<ExtractResponse | null> {
  try {
    return await extractionApi.fetch<ExtractResponse>('/extract', {
      method: 'POST',
      body: JSON.stringify({ text, taskId, modelId }),
    });
  } catch {
    return null;
  }
}

export async function extractTranscript(text: string): Promise<ExtractResponse | null> {
  return extractText(text, 'transcript-extraction');
}

export async function extractBatch(
  inputs: Array<{ text: string; taskId?: string }>,
  modelId?: string
): Promise<ExtractResponse[] | null> {
  try {
    const result = await extractionApi.fetch<{ results: ExtractResponse[] }>('/extract/batch', {
      method: 'POST',
      body: JSON.stringify({ inputs, modelId }),
    });
    return result.results;
  } catch {
    return null;
  }
}

// ── Tasks ────────────────────────────────────────────────────────

export async function listTasks(productId?: string): Promise<ExtractionTask[]> {
  const qs = productId ? `?productId=${encodeURIComponent(productId)}` : '';
  try {
    return await extractionApi.fetch<ExtractionTask[]>(`/tasks${qs}`);
  } catch {
    return [];
  }
}

export async function getTask(id: string): Promise<ExtractionTask | null> {
  try {
    return await extractionApi.fetch<ExtractionTask>(`/tasks/${encodeURIComponent(id)}`);
  } catch {
    return null;
  }
}

// ── Health ───────────────────────────────────────────────────────

export async function getSidecarHealth(): Promise<{ status: string; sidecar?: unknown } | null> {
  try {
    return await extractionApi.fetch<{ status: string; sidecar?: unknown }>(
      '/extract/sidecar-health'
    );
  } catch {
    return null;
  }
}
