import {
  type ParsedUserMessage,
  parseUserMessage,
} from "../../claude-code/functions/parseUserMessage";
import type { ExtendedConversation } from "../../types";
import { extractFirstUserText } from "./extractFirstUserText";

const ignoreCommands = [
  "/clear",
  "/login",
  "/logout",
  "/exit",
  "/mcp",
  "/memory",
];

export const extractFirstUserMessage = (
  conversation: ExtendedConversation,
): ParsedUserMessage | undefined => {
  if (conversation.type !== "user") {
    return undefined;
  }

  if (conversation.isSidechain === true) {
    return undefined;
  }

  const firstUserText = extractFirstUserText(conversation);

  if (firstUserText === null) {
    return undefined;
  }

  if (
    firstUserText ===
    "Caveat: The messages below were generated by the user while running local commands. DO NOT respond to these messages or otherwise consider them in your response unless the user explicitly asks you to."
  ) {
    return undefined;
  }

  if (firstUserText === "Warmup") {
    return undefined;
  }

  const command = parseUserMessage(firstUserText);
  if (command.kind === "local-command") {
    return undefined;
  }

  if (
    command.kind === "command" &&
    ignoreCommands.includes(command.commandName)
  ) {
    return undefined;
  }

  return command;
};
