import {
  createDeviceActionArtifact,
  createGuidedProcedureArtifact,
  createKnowledgeLessonArtifact,
  createParameterChangeArtifact,
} from "@/lib/artifacts/mock";
import type { InteractionArtifact } from "@/lib/artifacts/types";

export type MockRouteHint =
  | "artifact_action"
  | "tool_call"
  | "knowledge_query"
  | "workflow_control"
  | "smalltalk"
  | "fallback";

export type MockNluResult = {
  modelVersion: string;
  domain: string;
  intent: string;
  confidence: number;
  slots: Record<string, string | number | boolean>;
  routeHint: MockRouteHint;
  candidateTools: Array<{
    toolName: string;
    confidence: number;
  }>;
  branchLabel: string;
  artifact?: InteractionArtifact;
  reply?: string;
};

const mockParameterValues: Record<string, string | number> = {
  主轴转速: 1200,
  水泵压力上限: 0.6,
  温度补偿: 0,
  进给速度: 480,
};

export function parseMockNlu(text: string): MockNluResult {
  const normalized = normalizeText(text);

  if (includesAny(normalized, ["开始调机", "进入调机", "调机流程", "按步骤处理"])) {
    return {
      modelVersion: "mock-bert-nlu-v1",
      domain: "guided_procedure",
      intent: "start_procedure",
      confidence: 0.96,
      slots: { procedureName: "主轴温度报警调机流程" },
      routeHint: "workflow_control",
      candidateTools: [{ toolName: "start_guided_procedure", confidence: 0.94 }],
      branchLabel: "流程工具",
      artifact: createGuidedProcedureArtifact(),
    };
  }

  const parameter = detectParameter(normalized);
  const value = detectNumber(normalized);
  if (parameter && value !== undefined && includesAny(normalized, ["调", "改", "设置", "补偿", "加到", "设为"])) {
    const unit = detectUnit(normalized, parameter);
    return {
      modelVersion: "mock-bert-nlu-v1",
      domain: "machine_parameter",
      intent: "set_parameter",
      confidence: 0.94,
      slots: { parameter, value, unit },
      routeHint: "tool_call",
      candidateTools: [{ toolName: "write_machine_parameter", confidence: 0.91 }],
      branchLabel: "高置信度 + 设备控制域",
      artifact: createParameterChangeArtifact({
        parameterName: parameter,
        currentValue: mockParameterValues[parameter] ?? "未读取",
        targetValue: value,
        unit,
        deviceName: "一号加工设备",
      }),
    };
  }

  const deviceAction = detectDeviceAction(normalized);
  if (deviceAction) {
    return {
      modelVersion: "mock-bert-nlu-v1",
      domain: "machine_control",
      intent: `${deviceAction.action}_device`,
      confidence: 0.93,
      slots: {
        deviceName: deviceAction.deviceName,
        action: deviceAction.action,
        deviceKind: deviceAction.deviceKind,
      },
      routeHint: "tool_call",
      candidateTools: [{ toolName: "control_industrial_device", confidence: 0.9 }],
      branchLabel: "高置信度 + 设备控制域",
      artifact: createDeviceActionArtifact(deviceAction),
    };
  }

  if (includesAny(normalized, ["报警", "怎么办", "说明书", "sop", "处理", "为什么", "知识", "查一下"])) {
    const topic = normalized.includes("冷却") ? "冷却泵无流量处理" : "主轴温度报警处理";
    return {
      modelVersion: "mock-bert-nlu-v1",
      domain: "equipment_knowledge",
      intent: "query_procedure",
      confidence: 0.86,
      slots: { topic },
      routeHint: "knowledge_query",
      candidateTools: [{ toolName: "search_equipment_knowledge", confidence: 0.83 }],
      branchLabel: "知识域 / 低置信度兜底",
      artifact: createKnowledgeLessonArtifact(topic),
    };
  }

  if (includesAny(normalized, ["你好", "天气", "谢谢", "你是谁", "随便聊"])) {
    return {
      modelVersion: "mock-bert-nlu-v1",
      domain: "smalltalk",
      intent: "chat",
      confidence: 0.77,
      slots: {},
      routeHint: "smalltalk",
      candidateTools: [],
      branchLabel: "smalltalk / fallback",
      reply: "这是通用对话内容，不生成工业 Artifact，也不会覆盖当前调机流程。",
    };
  }

  return {
    modelVersion: "mock-bert-nlu-v1",
    domain: "fallback",
    intent: "unknown",
    confidence: 0.41,
    slots: {},
    routeHint: "fallback",
    candidateTools: [],
    branchLabel: "fallback",
    reply: "Mock NLU 暂时没有识别到固定意图。可以试试：把主轴转速调到 1800、打开探照灯、打开水泵、主轴温度报警怎么办、开始调机流程。",
  };
}

function normalizeText(text: string) {
  return text.trim().toLowerCase().replace(/\s+/g, "");
}

function includesAny(text: string, keywords: string[]) {
  return keywords.some((keyword) => text.includes(keyword.toLowerCase()));
}

function detectParameter(text: string) {
  if (text.includes("转速")) return "主轴转速";
  if (text.includes("压力")) return "水泵压力上限";
  if (text.includes("温度补偿") || text.includes("补偿")) return "温度补偿";
  if (text.includes("进给")) return "进给速度";
  return undefined;
}

function detectNumber(text: string) {
  const match = text.match(/[-+]?\d+(?:\.\d+)?/);
  if (!match) return undefined;
  return Number(match[0]);
}

function detectUnit(text: string, parameter: string) {
  if (text.includes("rpm")) return "rpm";
  if (text.includes("mpa")) return "MPa";
  if (text.includes("度") || parameter.includes("温度")) return "°C";
  if (parameter.includes("转速")) return "rpm";
  if (parameter.includes("压力")) return "MPa";
  return "";
}

function detectDeviceAction(text: string):
  | {
      deviceName: string;
      action: "open" | "close" | "start" | "stop";
      deviceKind: "light" | "pump" | "fan" | "machine";
    }
  | undefined {
  const action = text.includes("关闭") || text.includes("关掉")
    ? "close"
    : text.includes("停止")
      ? "stop"
      : text.includes("启动") || text.includes("开始")
        ? "start"
        : text.includes("打开")
          ? "open"
          : undefined;

  if (!action) return undefined;

  if (text.includes("探照灯") || text.includes("灯")) {
    return { deviceName: "探照灯", action, deviceKind: "light" };
  }
  if (text.includes("水泵") || text.includes("泵")) {
    return { deviceName: "冷却水泵", action, deviceKind: "pump" };
  }
  if (text.includes("风机")) {
    return { deviceName: "除尘风机", action: action === "open" ? "start" : action, deviceKind: "fan" };
  }
  if (text.includes("生产") || text.includes("设备")) {
    return { deviceName: "一号加工设备", action: action === "open" ? "start" : action, deviceKind: "machine" };
  }

  return undefined;
}
