import { API_BASE_URL, streamSSE, type ComplianceResult, type SSEMessage } from './index';

export async function analyzeDocument(file: File): Promise<{ task_id: string; status: string }> {
  const formData = new FormData();
  formData.append('file', file);

  const response = await fetch(`${API_BASE_URL}/compliance/analyze`, {
    method: 'POST',
    body: formData,
  });

  if (!response.ok) {
    throw new Error(`Upload failed: ${response.status}`);
  }

  return response.json() as Promise<{ task_id: string; status: string }>;
}

export async function getComplianceResult(
  taskId: string
): Promise<ComplianceResult | { status: string; message: string }> {
  const response = await fetch(`${API_BASE_URL}/compliance/result/${taskId}`);

  if (!response.ok) {
    throw new Error(`Get result failed: ${response.status}`);
  }

  return response.json() as Promise<ComplianceResult | { status: string; message: string }>;
}

export function complianceChat(
  segmentId: number,
  query: string,
  segmentContext: string | undefined,
  onMessage: (data: SSEMessage) => void,
  onError?: (error: Error) => void,
  onComplete?: () => void
): void {
  void streamSSE<SSEMessage>(
    `/compliance/chat/${segmentId}`,
    { query, segment_context: segmentContext },
    onMessage,
    onError,
    onComplete,
  );
}

export type { ComplianceResult, SSEMessage };
