import { createOpenAI } from "@ai-sdk/openai";
import { streamText } from "ai";
import { z } from "zod";
import {
  createDeviceActionArtifact,
  createGuidedProcedureArtifact,
  createKnowledgeLessonArtifact,
  createParameterChangeArtifact,
} from "@/lib/artifacts/mock";

const qwen = createOpenAI({
  baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
  apiKey: process.env.DASHSCOPE_API_KEY,
});

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

export const maxDuration = 30;

export async function POST(req: Request) {
  const { messages } = await req.json();

  const result = await streamText({
    model: qwen("qwen-plus"),
    maxSteps: 2,
    system: [
      "你是工业生产设备的 AI 交互画布编排助手。",
      "你不要只输出大段文字；当用户要调参、控制设备、查询设备知识、进入调机流程时，优先调用工具生成 artifact。",
      "第一阶段只支持文字输入和鼠标点击，不要提 ASR、语音识别或权限分级。",
      "一次用户请求最多只能调用一个工具。",
      "工具调用完成后，用一句很短的话说明右侧画布已经生成了什么，绝不能再次调用同一个工具。",
      "当用户说确认、执行、下一步、已完成等短指令时，如果上文已有当前画布，尽量解释为操作当前画布。",
    ].join("\n"),
    messages,
    tools: {
      proposeParameterChange: {
        description: "生成工业参数修改可视化组件，展示当前值、目标值和确认按钮。",
        parameters: z.object({
          parameterName: z.string().describe("参数名称，例如 主轴转速、水泵压力上限、温度补偿"),
          targetValue: z.union([z.string(), z.number()]).describe("目标值"),
          unit: z.string().optional().describe("单位，例如 rpm、MPa、°C"),
          deviceName: z.string().optional().describe("设备名称"),
        }),
        execute: async ({ parameterName, targetValue, unit, deviceName }) => {
          const normalizedName = parameterName.includes("转速") ? "主轴转速" : parameterName;
          const currentValue = mockParameterValues[normalizedName] ?? "未读取";
          const artifact = createParameterChangeArtifact({
            parameterName: normalizedName,
            currentValue,
            targetValue,
            unit,
            deviceName,
          });

          return {
            llmSummary: `${normalizedName} 参数修改卡片已生成，当前值 ${currentValue}${unit ?? ""}，目标值 ${targetValue}${unit ?? ""}。`,
            artifact,
            executionRecord: {
              toolName: "proposeParameterChange",
              args: { parameterName: normalizedName, targetValue, unit, deviceName },
              resultCode: "MOCK_PREVIEW_CREATED",
              createdAt: new Date().toISOString(),
            },
          };
        },
      },
      controlIndustrialDevice: {
        description: "生成具象设备控制动画组件，例如打开探照灯、启动水泵、关闭风机。",
        parameters: z.object({
          deviceName: z.string().describe("设备名称，例如 探照灯、水泵、除尘风机"),
          action: z.enum(["open", "close", "start", "stop"]).describe("动作"),
          deviceKind: z.enum(["light", "pump", "fan", "machine"]).describe("设备类型"),
        }),
        execute: async ({ deviceName, action, deviceKind }) => {
          const artifact = createDeviceActionArtifact({ deviceName, action, deviceKind });

          return {
            llmSummary: `${deviceName} 的${action}动作卡片已生成，等待用户确认。`,
            artifact,
            executionRecord: {
              toolName: "controlIndustrialDevice",
              args: { deviceName, action, deviceKind },
              resultCode: "MOCK_PREVIEW_CREATED",
              createdAt: new Date().toISOString(),
            },
          };
        },
      },
      answerEquipmentKnowledge: {
        description: "生成设备说明书、报警处理或调机知识的教学式卡片。",
        parameters: z.object({
          topic: z.string().describe("知识主题，例如 主轴温度报警处理、冷却泵无流量怎么办"),
        }),
        execute: async ({ topic }) => {
          const artifact = createKnowledgeLessonArtifact(topic);

          return {
            llmSummary: `${topic} 的教学式知识卡片已生成。`,
            artifact,
            executionRecord: {
              toolName: "answerEquipmentKnowledge",
              args: { topic },
              resultCode: "MOCK_KNOWLEDGE_CREATED",
              createdAt: new Date().toISOString(),
            },
          };
        },
      },
      startGuidedProcedure: {
        description: "生成一个 3 到 5 步的引导式调机流程组件。",
        parameters: z.object({
          procedureName: z.string().optional().describe("流程名称"),
        }),
        execute: async () => {
          const artifact = createGuidedProcedureArtifact();

          return {
            llmSummary: "主轴温度报警调机流程已经生成，当前等待第 1 步反馈。",
            artifact,
            executionRecord: {
              toolName: "startGuidedProcedure",
              args: {},
              resultCode: "MOCK_PROCEDURE_CREATED",
              createdAt: new Date().toISOString(),
            },
          };
        },
      },
    },
  });

  return result.toDataStreamResponse();
}
