/**
 * src/lib/artifacts/factory.ts
 *
 * NLU 结果 → Artifact 工厂
 *
 * 根据 NluResult（domain / intent / slots）构造对应的 InteractionArtifact。
 * 返回 null 表示该 intent 不需要展示 Artifact（纯文字回复即可）。
 *
 * ── 配置指南 ────────────────────────────────────────────────────────────────
 *
 * 1. 新增工具的 Artifact：
 *    在 INTENT_TO_ARTIFACT 表里加一条 case，返回对应 InteractionArtifact。
 *
 * 2. 已有 Artifact 类型的结构：
 *    参见 src/lib/artifacts/types.ts 里的 ParameterChangeProps / DeviceActionProps 等。
 *
 * 3. 对应的可视化组件：
 *    src/components/artifacts/ArtifactRenderer.tsx 底部的 registry 对象，
 *    key = ArtifactType，value = React 组件。新增 artifact_type 时在此注册。
 *
 * 4. 对应的 Python 工具实现：
 *    intelligent_cabin/app/plugins/mock.py —— 注册 plugin_id → 执行函数
 *    intelligent_cabin/config/actions.yml  —— action_id → plugin_id 映射
 *    intelligent_cabin/config/domain.yml   —— intent_id → action_id 映射
 */

import { createParameterChangeArtifact } from "./mock";
import type { DieMaterialAdjustProps, DieStatusOverviewProps, InteractionArtifact } from "./types";
import { generateDiePositions, generateDieStatusOverview } from "./die-mock-data";
import type { NluResult } from "@/lib/nlu/types";


// ── 统一确认/取消按钮（所有需要确认的操作共用） ──────────────────────────────
// 如需修改语音别名，在此处或 voice_aliases.yml 中调整
const CONFIRM_VOICE_ALIASES = ["确认执行", "可以执行", "执行吧", "确认", "好的"];
const CANCEL_VOICE_ALIASES = ["取消执行", "不要执行", "先别执行", "取消", "算了"];

function makeConfirmActions() {
  return [
    {
      actionId: "artifact.confirm",
      label: "确认执行",
      kind: "primary" as const,
      textAliases: ["确认", "确认执行", "执行", "开始执行", "确定", "没问题"],
      voiceAliases: CONFIRM_VOICE_ALIASES,
      requiresConfirmation: true,
    },
    {
      actionId: "artifact.cancel",
      label: "取消",
      kind: "secondary" as const,
      textAliases: ["取消", "先不执行", "不要"],
      voiceAliases: CANCEL_VOICE_ALIASES,
    },
  ];
}

// ── 主映射函数 ────────────────────────────────────────────────────────────────

/**
 * 根据 NLU 识别结果构造 Artifact。
 * 返回 null 时前端只显示文字回复，不渲染 Artifact 卡片。
 */
export function buildArtifactFromNlu(result: NluResult): InteractionArtifact | null {
  const { intent, slots } = result;

  switch (intent) {

    // ── 空调温度设置 ─────────────────────────────────────────────────────────
    // Python 链路：cabin_set_ac → action_cabin_set_ac → plugin.cabin.ac_control → mock._set_ac()
    // 可视化：ParameterChangeCard（src/components/artifacts/ArtifactRenderer.tsx）
    case "cabin_set_ac": {
      const targetTemp = slots["temperature"] ?? slots["value"] ?? "?";
      const currentTemp = 25; // 实际项目：从设备读取当前温度
      return createParameterChangeArtifact({
        parameterName: "空调温度",
        currentValue: currentTemp,
        targetValue: Number(targetTemp),
        unit: "°C",
        deviceName: "车载空调",
      });
    }

    // ── 以下 intent 只返回文字，不需要 Artifact ───────────────────────────────
    case "cabin_ac_on":
    case "cabin_ac_off":
    case "cabin_fan_up":
    case "cabin_fan_down":
    case "cabin_nav_cancel":
    case "cabin_play_music":
    case "cabin_pause_music":
    case "cabin_next_track":
    case "cabin_previous_track":
    case "cabin_volume_up":
    case "cabin_volume_down":
    case "cabin_volume_mute":
    case "cabin_lights_on":
    case "cabin_lights_off":
    case "cabin_seat_heat_on":
    case "cabin_seat_heat_off":
    case "cabin_mirror_fold":
    case "cabin_mirror_unfold":
    case "cabin_wiper_on":
    case "cabin_wiper_off":
    case "cabin_window_open":
    case "cabin_window_close":
    case "cabin_sunroof_open":
    case "cabin_sunroof_close":
    case "cabin_defog_front_on":
    case "cabin_defog_rear_on":
    case "cabin_lock_doors":
    case "cabin_unlock_doors":
      return null; // 执行成功，回复 replyText 即可

    // ── 需要补槽（ask_slot），不展示确认卡片 ──────────────────────────────────
    case "cabin_nav_to":
      return null;

    default:
      return null;
  }
}

// ── 独立 Artifact 构建器（用于演示按钮直接触发）─────────────────────────────────

/** 构建知识检索卡：虚焊报警 / 弯管工序 / 激光扫描仪 */
export function buildFalseWeldKnowledgeArtifact(): InteractionArtifact {
  return {
    artifactId: `knowledge_${Date.now()}`,
    type: "knowledge_lesson",
    title: "虚焊报警处理 — 弯管工序",
    status: "success",
    props: {
      topic: "虚焊报警 / 涡流探伤 / 弯管成形偏差",
      conclusion:
        "弯管工序成形形态偏差是虚焊报警的主要原因。用激光扫描仪检测各模具点位，偏差超限时通过平板 AI 自动调节后再验证。",
      blocks: [
        {
          type: "summary",
          text: "涡流探伤报警（虚焊）通常来自管材表面形态异常，而形态偏差源头在弯管工序的模具成形质量。需用激光扫描仪逐点检测，找到偏差超限的模具后自动调节。",
        },
        {
          type: "key_points",
          items: ["定位报警管段对应模具区间", "激光扫描每个模具出口点位", "偏差 >0.30mm 立即 AI 自动调节", "调节后生产 1~2m 再验证"],
        },
        {
          type: "steps",
          steps: [
            {
              title: "停机 & 确认报警位置",
              body: "在涡流探伤仪界面记录报警触发时的管材位置，折算到对应的弯管模具区间。",
            },
            {
              title: "激光扫描检测",
              body: "打开平板 App → 弯管检测 → 开始扫描。扫描仪逐一采集每个模具出口横截面，约 2s/点。",
              media: [
                {
                  type: "image",
                  title: "扫描仪安装位置",
                  description: "激光线垂直于管材轴线，安装于模具出口侧",
                  url: "/assets/knowledge/laser_scan_setup.jpg",
                },
                {
                  type: "video",
                  title: "激光扫描完整操作流程",
                  description: "约 4 分钟，含校准 + 扫描 + 报告生成",
                  url: "/assets/knowledge/laser_scan_tutorial.mp4",
                },
              ],
            },
            {
              title: "查看差异云图",
              body: "扫描完成后点击「生成报告」，平板 App 显示差异云图：绿色=正常，黄色=警告（>0.15mm），红色=超限（>0.30mm）。",
              media: [
                {
                  type: "image",
                  title: "平板 App 差异云图",
                  description: "红色区域即需要调节的模具",
                  url: "/assets/knowledge/tablet_deviation_map.jpg",
                },
              ],
            },
            {
              title: "AI 自动调节",
              body: "对红色（超限）模具点击「AI 自动调节」，系统计算补偿量后自动写入伺服位置，约 15s 完成。",
            },
            {
              title: "验证",
              body: "调节完毕后开机生产约 1~2m，重新扫描确认偏差已回到绿色范围，再恢复正常生产速度。",
            },
          ],
        },
        {
          type: "details",
          title: "偏差判定标准（参考表）",
          markdown:
            "正常：≤ ±0.15mm，无需处理。\n警告：±0.15～0.30mm，记录并于下次保养处理。\n超限：> ±0.30mm，立即停机调节。\n\n注：以上阈值适用于 20mm 圆管，其他规格请参考《焊管机维护手册》第 7 章。",
          defaultOpen: false,
        },
        {
          type: "citations",
          citations: [
            { title: "焊管机维护手册", location: "第 7 章：弯管工序成形质量管理" },
            { title: "激光扫描仪操作规程", location: "SOP-QC-003 v1.2" },
            { title: "涡流探伤报警处置流程", location: "SOP-QC-007 v2.0" },
          ],
        },
      ],
    },
    actions: [],
    llmContext: {
      visibleSummary: "正在显示虚焊报警（弯管工序）的知识卡片，含激光扫描仪操作和 AI 自动调节步骤。",
      currentState: "success",
      visibleFields: [{ label: "主题", value: "虚焊报警 / 弯管工序 / 激光扫描" }],
      availableActions: [],
      lastEvents: [],
    },
    snapshotPolicy: "ephemeral",
  };
}

/** 构建模具伺服调节 Artifact（材料 + 尺寸驱动） */
export function buildDieMaterialAdjustArtifact(params?: {
  material?: string;
  outerDiameter?: number;
  thickness?: number;
}): InteractionArtifact {
  const material = params?.material ?? "304 不锈钢";
  const outerDiameter = params?.outerDiameter ?? 20;
  const thickness = params?.thickness ?? 2;
  const dies = generateDiePositions({ outerDiameter, thickness, totalDies: 15 });
  const overCount = dies.filter((d) => d.status === "over_limit").length;

  const props: DieMaterialAdjustProps = {
    material,
    outerDiameter,
    thickness,
    pipeShape: "round",
    totalDies: 15,
    dies,
    executionNote:
      overCount > 0
        ? `检测到 ${overCount} 个模具位置超限，点击「AI 自动调节」将自动写入补偿量。`
        : "所有模具位置在正常范围内，可按当前参数生产。",
  };

  return {
    artifactId: `die_adjust_${Date.now()}`,
    type: "die_material_adjust",
    title: `模具伺服调节 — ${material} Φ${outerDiameter}×${thickness}`,
    status: overCount > 0 ? "waiting_confirmation" : "success",
    props,
    actions:
      overCount > 0
        ? [
            {
              actionId: "artifact.confirm",
              label: "AI 自动调节",
              kind: "primary" as const,
              textAliases: ["自动调节", "调节", "确认", "执行"],
              voiceAliases: ["自动调节", "AI 调节", "确认调节"],
              requiresConfirmation: true,
            },
            {
              actionId: "artifact.cancel",
              label: "取消",
              kind: "secondary" as const,
              textAliases: ["取消"],
              voiceAliases: ["取消", "不调节"],
            },
          ]
        : [],
    llmContext: {
      visibleSummary: `正在显示 ${material} Φ${outerDiameter}mm 管材的 15 个模具伺服位置，${overCount > 0 ? `${overCount} 个超限` : "全部正常"}。`,
      currentState: overCount > 0 ? "waiting_confirmation" : "success",
      visibleFields: [
        { label: "材料", value: material },
        { label: "外径", value: `${outerDiameter} mm` },
        { label: "壁厚", value: `${thickness} mm` },
        { label: "超限数量", value: String(overCount) },
      ],
      availableActions: [],
      lastEvents: [],
    },
    snapshotPolicy: "session",
  };
}

/** 构建模具位置总览 Artifact（16 个模具，可点击查看截面） */
export function buildDieStatusOverviewArtifact(): InteractionArtifact {
  const dies = generateDieStatusOverview(16);
  const props: DieStatusOverviewProps = {
    totalDies: 16,
    selectedDieIndex: null,
    dies,
    lastScanTime: new Date().toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" }),
  };

  return {
    artifactId: `die_overview_${Date.now()}`,
    type: "die_status_overview",
    title: "弯管模具位置总览",
    status: "success",
    props,
    actions: [],
    llmContext: {
      visibleSummary: "正在显示全部 16 个弯管模具的当前位置和截面形态，可点击任意模具查看详情。",
      currentState: "success",
      visibleFields: [{ label: "模具总数", value: "16" }],
      availableActions: [],
      lastEvents: [],
    },
    snapshotPolicy: "session",
  };
}


// 导出供 page.tsx 使用
export { makeConfirmActions };
