// SPEC: pikasTech/HWLAB#2345 Workbench Pinia Colada migration; PJ2026-010401080313 Workbench实时权威 draft-2026-07-08-p0-workbench-realtime-authority-v2.
// Responsibility: Colada-governed Workbench mutation execution and semantic query invalidation.

import { useMutation, useQueryCache } from "@pinia/colada";
import { api } from "@/api";
import type { ApiRequestOptions } from "@/api/client";
import type { AgentChatResponse, ApiResult } from "@/types";
import { firstNonEmptyString } from "@/utils";
import { workbenchColadaKeys } from "./workbench-colada-keys";

export interface WorkbenchAgentMutationInput {
  payload: Record<string, unknown>;
  timeoutMs: number;
  activityRef?: ApiRequestOptions["activityRef"];
  sessionId?: string | null;
  traceId?: string | null;
}

export interface WorkbenchCancelMutationInput {
  traceId: string;
  sessionId?: string | null;
  threadId?: string | null;
}

export interface WorkbenchColadaMutations {
  createAgentSession: (payload?: Record<string, unknown>) => Promise<ApiResult<{ session?: Record<string, unknown> }>>;
  submitAgentMessage: (input: WorkbenchAgentMutationInput) => Promise<ApiResult<AgentChatResponse>>;
  steerAgentMessage: (input: WorkbenchAgentMutationInput) => Promise<ApiResult<AgentChatResponse>>;
  cancelAgentMessage: (input: WorkbenchCancelMutationInput) => Promise<ApiResult<AgentChatResponse & { canceled?: boolean; alreadyTerminal?: boolean; cancelStatus?: string; error?: { code?: string; message?: string; userMessage?: string } }>>;
  deleteAgentSession: (input: { sessionId: string }) => Promise<ApiResult<{ ok?: boolean; status?: string; session?: Record<string, unknown>; archivedCount?: number }>>;
}

export function useWorkbenchColadaMutations(): WorkbenchColadaMutations {
  const queryCache = useQueryCache();
  const createSessionMutation = useMutation<ApiResult<{ session?: Record<string, unknown> }>, Record<string, unknown> | undefined>({
    key: workbenchColadaKeys.mutationCreateSession(),
    mutation: (payload) => api.agent.createAgentSession(payload ?? {}),
    onSettled: () => { void queryCache.invalidateQueries({ key: workbenchColadaKeys.snapshotRoot() }); }
  });
  const submitMutation = useMutation<ApiResult<AgentChatResponse>, WorkbenchAgentMutationInput>({
    key: workbenchColadaKeys.mutationSubmit(),
    mutation: (input) => api.agent.sendAgentMessage(input.payload, input.timeoutMs, input.activityRef),
    onSettled: (result, _error, input) => { void invalidateMutationScope(queryCache, input.sessionId, firstNonEmptyString(result?.data?.traceId, input.traceId)); }
  });
  const steerMutation = useMutation<ApiResult<AgentChatResponse>, WorkbenchAgentMutationInput>({
    key: workbenchColadaKeys.mutationSteer(),
    mutation: (input) => api.agent.steerAgentMessage(input.payload, input.timeoutMs, input.activityRef),
    onSettled: (result, _error, input) => { void invalidateMutationScope(queryCache, input.sessionId, firstNonEmptyString(result?.data?.traceId, input.traceId)); }
  });
  const cancelMutation = useMutation<ApiResult<AgentChatResponse & { canceled?: boolean; alreadyTerminal?: boolean; cancelStatus?: string; error?: { code?: string; message?: string; userMessage?: string } }>, WorkbenchCancelMutationInput>({
    key: (input) => workbenchColadaKeys.mutationCancel(input.traceId),
    mutation: (input) => api.agent.cancelAgentMessage({ traceId: input.traceId, sessionId: input.sessionId, threadId: input.threadId }),
    onSettled: (_result, _error, input) => { void invalidateMutationScope(queryCache, input.sessionId, input.traceId); }
  });
  const deleteMutation = useMutation<ApiResult<{ ok?: boolean; status?: string; session?: Record<string, unknown>; archivedCount?: number }>, { sessionId: string }>({
    key: (input) => workbenchColadaKeys.mutationDeleteSession(input.sessionId),
    mutation: (input) => api.agent.deleteAgentSession(input.sessionId),
    onSettled: (_result, _error, input) => { void invalidateMutationScope(queryCache, input.sessionId, null); }
  });

  return {
    createAgentSession: (payload) => createSessionMutation.mutateAsync(payload),
    submitAgentMessage: (input) => submitMutation.mutateAsync(input),
    steerAgentMessage: (input) => steerMutation.mutateAsync(input),
    cancelAgentMessage: (input) => cancelMutation.mutateAsync(input),
    deleteAgentSession: (input) => deleteMutation.mutateAsync(input)
  };
}

async function invalidateMutationScope(queryCache: ReturnType<typeof useQueryCache>, sessionId: string | null | undefined, traceId: string | null | undefined): Promise<void> {
  await Promise.all([
    queryCache.invalidateQueries({ key: workbenchColadaKeys.snapshotRoot() }),
    sessionId ? queryCache.invalidateQueries({ key: workbenchColadaKeys.historySessionMessagesRoot().concat(sessionId) }) : Promise.resolve(),
    traceId ? queryCache.invalidateQueries({ key: workbenchColadaKeys.detailRoot() }) : Promise.resolve()
  ]);
}
