import type { Message, ToolDef } from '../../llm/openai-compat.js';
import { loadConfig } from '../../config.js';
import { getToolDefs, type ToolContext } from '../tools/index.js';
import type { Conversation } from '../context/conversation.js';
import type { HandoffContext, Movement } from './types.js';
import { buildGlobalPreamble, buildMovementGuidance } from './prompt.js';
import { buildCompleteTool, buildTransitionTool } from './terminal-control.js';

export interface PreparedMovement {
  regularTools: ToolDef[];
  tools: ToolDef[];
  messages: Message[];
}

export const prepareMovement = async (args: {
  movement: Movement;
  taskInstruction: string;
  ctx: ToolContext;
  conversation?: Conversation;
  priorTurns?: Message[];
  handoffContext?: HandoffContext;
  visitCount: number;
  maxVisits: number;
}): Promise<PreparedMovement> => {
  const {
    movement,
    taskInstruction,
    ctx,
    conversation,
    priorTurns,
    handoffContext,
    visitCount,
    maxVisits,
  } = args;

  const regularTools = await getToolDefs(movement.allowedTools, movement.edit, {
    vlmEnabled: ctx.vlmEnabled,
    ownerId: ctx.ownerId ?? null,
    mcpDisabled: ctx.mcpDisabled,
    spaceId: ctx.spaceId ?? null,
  });
  const transitionTool = movement.rules.length > 0 ? buildTransitionTool(movement.rules) : null;
  const completeTool = buildCompleteTool();
  const tools = transitionTool
    ? [...regularTools, transitionTool, completeTool]
    : [...regularTools, completeTool];

  const config = loadConfig();
  const userFolderRoot = config.userFolderRoot ?? './data/users';
  const skillFolder = ctx.folderContext ?? { rootDir: userFolderRoot, leafId: ctx.userId ?? 'local' };
  const skillIndex = ctx.skillsDisabled ? '' : (ctx.skillCatalog?.buildIndexForFolder(skillFolder.rootDir, skillFolder.leafId) ?? '');
  const needPreamble = !conversation || conversation.messages.length === 0;
  const hasPriorTurns = (priorTurns?.length ?? 0) > 0;
  const preamble = needPreamble
    ? buildGlobalPreamble(regularTools, {
        missionBrief: ctx.missionBrief?.read(),
        userId: ctx.userId,
        userFolderRoot,
        workspacePath: ctx.workspacePath,
        taskId: ctx.taskId ?? null,
        handoffContext: hasPriorTurns ? undefined : handoffContext,
        skillIndex,
        folderContext: ctx.folderContext,
        movementForConsole: movement,
      })
    : '';
  const guidance = buildMovementGuidance(movement, visitCount, maxVisits);

  if (conversation) {
    if (conversation.messages.length === 0) {
      if (hasPriorTurns) {
        conversation.seedContinuation(preamble, guidance, priorTurns!, taskInstruction);
      } else {
        conversation.seed(preamble, guidance, taskInstruction);
      }
    } else {
      conversation.enterMovement(guidance);
    }
    return { regularTools, tools, messages: conversation.messages };
  }

  return {
    regularTools,
    tools,
    messages: [
      { role: 'system', content: `${preamble}\n\n${guidance}` },
      { role: 'user', content: taskInstruction },
    ],
  };
};
