import type { ArtifactAction, ArtifactActionEvent, InteractionArtifact } from "./types";

export function createActionEvent(
  artifactId: string,
  action: ArtifactAction,
  source: ArtifactActionEvent["source"],
  value?: unknown,
  transcript?: string,
): ArtifactActionEvent {
  return {
    artifactId,
    actionId: action.actionId,
    source,
    value,
    transcript,
    createdAt: new Date().toISOString(),
  };
}

export function updateArtifactForAction(artifact: InteractionArtifact, event: ArtifactActionEvent): InteractionArtifact {
  if (event.actionId === "artifact.cancel") {
    return {
      ...artifact,
      status: "paused",
      llmContext: {
        ...artifact.llmContext,
        currentState: "paused",
        lastEvents: [...artifact.llmContext.lastEvents, "用户取消了当前操作。"],
      },
    };
  }

  if (event.actionId === "artifact.confirm") {
    if (artifact.type === "parameter_change") {
      return {
        ...artifact,
        status: "success",
        actions: [],
        llmContext: {
          ...artifact.llmContext,
          currentState: "success",
          visibleSummary: `${artifact.props.parameterName} 已从 ${artifact.props.currentValue}${artifact.props.unit ?? ""} 修改为 ${artifact.props.targetValue}${artifact.props.unit ?? ""}。`,
          lastEvents: [...artifact.llmContext.lastEvents, "用户确认并完成参数修改。"],
        },
      };
    }

    if (artifact.type === "device_action") {
      return {
        ...artifact,
        status: "success",
        props: {
          ...artifact.props,
          currentState: artifact.props.targetState,
          progressLabel: "状态回读完成",
        },
        actions: [],
        llmContext: {
          ...artifact.llmContext,
          currentState: "success",
          visibleSummary: `${artifact.props.deviceName} 已切换到 ${artifact.props.targetState}。`,
          lastEvents: [...artifact.llmContext.lastEvents, "用户确认并完成设备动作。"],
        },
      };
    }
  }

  if (event.actionId === "procedure.pause" && artifact.type === "guided_procedure") {
    return {
      ...artifact,
      status: "paused",
      llmContext: {
        ...artifact.llmContext,
        currentState: "paused",
        lastEvents: [...artifact.llmContext.lastEvents, "用户暂停了调机流程。"],
      },
    };
  }

  if (event.actionId === "procedure.next" && artifact.type === "guided_procedure") {
    const currentIndex = artifact.props.steps.findIndex((step) => step.stepId === artifact.props.currentStepId);
    const nextIndex = currentIndex + 1;
    const nextStep = artifact.props.steps[nextIndex];
    const updatedSteps = artifact.props.steps.map((step, index) => {
      if (index === currentIndex) return { ...step, status: "completed" as const, value: String(event.value ?? event.transcript ?? "") };
      if (index === nextIndex) return { ...step, status: "waiting_feedback" as const };
      return step;
    });

    if (!nextStep) {
      return {
        ...artifact,
        status: "success",
        actions: [],
        props: {
          ...artifact.props,
          steps: updatedSteps,
        },
        llmContext: {
          ...artifact.llmContext,
          currentState: "success",
          visibleSummary: `${artifact.props.procedureName} 已完成。`,
          activeStep: undefined,
          lastEvents: [...artifact.llmContext.lastEvents, "调机流程已完成。"],
        },
      };
    }

    return {
      ...artifact,
      status: "running",
      props: {
        ...artifact.props,
        currentStepId: nextStep.stepId,
        steps: updatedSteps,
      },
      llmContext: {
        ...artifact.llmContext,
        currentState: "running",
        activeStep: nextStep.title,
        visibleSummary: `调机流程进入下一步：${nextStep.title}。`,
        visibleFields: [{ label: "当前步骤", value: nextStep.title }],
        lastEvents: [...artifact.llmContext.lastEvents, `进入步骤：${nextStep.title}`],
      },
    };
  }

  return artifact;
}

export function matchTextToAction(artifact: InteractionArtifact, text: string): ArtifactAction | undefined {
  const normalized = normalizeActionText(text);
  const explicitAction = artifact.actions.find((action) =>
    [...action.textAliases, ...(action.voiceAliases ?? [])].some((alias) => {
      const normalizedAlias = normalizeActionText(alias);
      return normalized === normalizedAlias || normalized.includes(normalizedAlias);
    }),
  );

  if (explicitAction) return explicitAction;

  if (artifact.type === "guided_procedure") {
    const activeStep = artifact.props.steps.find((step) => step.stepId === artifact.props.currentStepId);
    const nextAction = artifact.actions.find((action) => action.actionId === "procedure.next");

    if (!activeStep || !nextAction) return undefined;

    const matchesExpectedFeedback = activeStep.expectedFeedback?.some((feedback) => {
      const normalizedFeedback = normalizeActionText(feedback);
      return normalized === normalizedFeedback || normalized.includes(normalizedFeedback);
    });

    if (matchesExpectedFeedback) return nextAction;

    if (activeStep.type === "measurement_input" && /[-+]?\d+(?:\.\d+)?/.test(normalized)) {
      return nextAction;
    }
  }

  return undefined;
}

function normalizeActionText(text: string) {
  return text
    .trim()
    .toLowerCase()
    .replace(/^(语音|voice|asr)[:：]/, "")
    .replace(/[\s，。,.！!？?、]/g, "");
}
