import { useMutation, useQuery } from '@tanstack/react-query';
import { apiFetch } from '../lib/api';
import type { Settings } from '../lib/types';

interface AIResult {
  text?: string;
  error?: string;
}

interface AICallArgs {
  task: string;
  params: Record<string, string>;
}

export function useAI() {
  const { data: settings } = useQuery({
    queryKey: ['settings'],
    queryFn: () => apiFetch<Settings>('/settings'),
    retry: false,
  });

  const hasProvider =
    !!settings?.ai_key_set &&
    settings.ai_provider !== 'none';

  const run = useMutation({
    mutationFn: ({ task, params }: AICallArgs) =>
      apiFetch<AIResult>('/ai/proxy', {
        method: 'POST',
        body: JSON.stringify({ task, params }),
      }),
  });

  return { run, hasProvider, settings };
}
