import type { Message } from "./GlobalChatbox.types";
import type {
  AgentQuestionRequest,
  AgentTodoUpdate,
} from "@/lib/chatStream";

export const createId = () =>
  `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
export const PRESET_PROMPTS = [
  "分析当前管网中的水力瓶颈管道，并给出改造建议。",
  "供水服务分区分析。",
  "帮我分析当前管网压力异常点，并按风险等级排序。",
  "帮我生成一份今日运行简报，包含问题、原因和建议。",
  "查询关键 SCADA 点位最近 24 小时的异常波动。",
  "排查当前管网爆管风险，并说明优先处置建议。",
];

export const stripMarkdown = (md: string): string =>
  md
    .replace(/```[\s\S]*?```/g, "")
    .replace(/`([^`]+)`/g, "$1")
    .replace(/!\[.*?\]\(.*?\)/g, "")
    .replace(/\[([^\]]+)\]\(.*?\)/g, "$1")
    .replace(/#{1,6}\s+/g, "")
    .replace(/\*\*\*(.+?)\*\*\*/g, "$1")
    .replace(/\*\*(.+?)\*\*/g, "$1")
    .replace(/\*(.+?)\*/g, "$1")
    .replace(/~~(.+?)~~/g, "$1")
    .replace(/>\s+/g, "")
    .replace(/[-*+]\s+/g, "")
    .replace(/\d+\.\s+/g, "")
    .replace(/\n{2,}/g, "\n")
    .replace(/<[^>]+>/g, "")
    .trim();

const normalizeQuestionRequests = (
  questions: Message["questions"],
): Message["questions"] =>
  Array.isArray(questions)
    ? questions.map((request) => ({
        ...request,
        questions: Array.isArray(request.questions)
          ? request.questions.map((question) => ({
              ...question,
              header: typeof question.header === "string" ? question.header : "",
              question:
                typeof question.question === "string" ? question.question : "",
              options: Array.isArray(question.options)
                ? question.options.map((option) => ({
                    label:
                      typeof option.label === "string" ? option.label : "",
                    description:
                      typeof option.description === "string"
                        ? option.description
                        : "",
                  }))
                : [],
            }))
          : [],
        answers: Array.isArray(request.answers)
          ? request.answers.map((answer) =>
              Array.isArray(answer)
                ? answer.filter((item): item is string => typeof item === "string")
                : [],
            )
          : undefined,
      } satisfies AgentQuestionRequest))
    : undefined;

const normalizeTodoUpdate = (todos: Message["todos"]): Message["todos"] => {
  if (!todos) return undefined;
  return {
    ...todos,
    todos: Array.isArray(todos.todos)
      ? todos.todos.map((todo) => ({ ...todo }))
      : [],
  } satisfies AgentTodoUpdate;
};

export const cloneMessage = (message: Message): Message => ({
  ...message,
  progress: Array.isArray(message.progress) ? [...message.progress] : undefined,
  artifacts: Array.isArray(message.artifacts) ? [...message.artifacts] : undefined,
  permissions: Array.isArray(message.permissions)
    ? message.permissions.map((permission) => ({
        ...permission,
        patterns: Array.isArray(permission.patterns)
          ? [...permission.patterns]
          : [],
        always: Array.isArray(permission.always) ? [...permission.always] : [],
      }))
    : undefined,
  questions: normalizeQuestionRequests(message.questions),
  todos: normalizeTodoUpdate(message.todos),
});

export const cloneMessages = (messages: Message[]) => messages.map(cloneMessage);
