import { useQuery } from '@tanstack/react-query';
import { useClient } from 'hooks/useClient';
import { useCapabilities } from 'hooks/useCapabilities';
import { type TriggerConfig, groupByCategory, matchesTrigger } from './useTasks';

export type AgentSummary = {
  dirName: string;
  name: string;
  description: string | null;
  category: string | null;
  triggers: TriggerConfig[];
};

export type AgentGroup = { category: string; agents: AgentSummary[] };

// Agents share the task trigger/category vocabulary, but they are a separate item type and get their
// own submenu — an agent run is a chat session, not a job, so mixing the two menus would promise the
// wrong thing about what happens when you click.
export const useAgents = () => {
  const client = useClient();
  // Agents are the `items` capability — skills, tools and agents on the owner's disk — and running one
  // starts a chat session, which is `chat`. Both are execution-only, so a member gets no agent submenu.
  const { can } = useCapabilities();
  const allowed = can('items');

  const { data: agents = [] } = useQuery<AgentSummary[]>({
    queryKey: ['agents'],
    enabled: allowed,
    queryFn: () => client.get('/agents'),
    staleTime: 60_000,
  });

  const { data: categoryOrder = [] } = useQuery<string[]>({
    queryKey: ['agent-categories'],
    enabled: allowed,
    queryFn: () => client.get('/agents/categories'),
    staleTime: 60_000,
  });

  const getMatchingAgents = (fileName: string, entryType: 'file' | 'directory'): AgentSummary[] =>
    agents.filter((a) => matchesTrigger(a.triggers, fileName, entryType));

  const getMatchingAgentGroups = (fileName: string, entryType: 'file' | 'directory'): AgentGroup[] =>
    groupByCategory(getMatchingAgents(fileName, entryType), categoryOrder).map(({ category, items }) => ({
      category,
      agents: items,
    }));

  return { agents, categoryOrder, getMatchingAgents, getMatchingAgentGroups };
};
