import type {
  AgentApiClient,
  AgentChatSessionSummary,
  AgentModelOption
} from "./client";
import { parseUiRegistry, type UIRegistry } from "../ui-envelope";
import { parseFrontendActionRegistry, type FrontendActionRegistry } from "../frontend-action";

export const agentBootstrapKey = ["agent", "bootstrap"] as const;
export const agentSessionsKey = ["agent", "sessions"] as const;

export type AgentBootstrapData = {
  registry: UIRegistry | null;
  frontendActionRegistry?: FrontendActionRegistry | null;
  models: AgentModelOption[];
  defaultModel: string;
};

export async function fetchAgentBootstrap(client: AgentApiClient): Promise<AgentBootstrapData> {
  const [rawRegistry, rawFrontendActionRegistry, modelsResponse] = await Promise.all([
    client.getUiRegistry(),
    typeof client.getFrontendActionRegistry === "function" ? client.getFrontendActionRegistry() : Promise.resolve(undefined),
    client.getModels()
  ]);

  return {
    registry: parseUiRegistry(rawRegistry),
    ...(rawFrontendActionRegistry === undefined ? {} : { frontendActionRegistry: parseFrontendActionRegistry(rawFrontendActionRegistry) }),
    models: modelsResponse.models,
    defaultModel: modelsResponse.defaultModel
  };
}

export async function fetchAgentSessions(client: AgentApiClient): Promise<AgentChatSessionSummary[]> {
  return client.listSessions();
}
