/**
 * src/lib/artifacts/die-mock-data.ts
 *
 * 模具模拟数据生成器。
 * 实际接入时替换为从 PLC / 伺服驱动器读取的真实数据。
 */

import type { DiePositionData } from "./types";

/** 根据材料和尺寸生成 15 个模具的模拟伺服位置 */
export function generateDiePositions(params: {
  outerDiameter: number;
  thickness: number;
  totalDies?: number;
}): DiePositionData[] {
  const count = params.totalDies ?? 15;
  const r = params.outerDiameter / 2;

  return Array.from({ length: count }, (_, i) => {
    const idx = i + 1;
    // 模拟：越靠后的模具偏差越小（成形收敛）
    const progressRatio = idx / count;
    const baseX = +(r * 0.1 * (1 - progressRatio)).toFixed(3);
    const baseY = +(r * 0.08 * (1 - progressRatio)).toFixed(3);

    // 当前值 = 标准值 + 随机扰动
    const noise = () => +(Math.random() * 0.4 - 0.2).toFixed(3);
    const stdX = +baseX.toFixed(3);
    const stdY = +baseY.toFixed(3);
    const curX = +(stdX + noise()).toFixed(3);
    const curY = +(stdY + noise()).toFixed(3);
    const curAngle = +(noise() * 0.5).toFixed(3);
    const deviation = +Math.sqrt((curX - stdX) ** 2 + (curY - stdY) ** 2).toFixed(3);

    const status: DiePositionData["status"] =
      deviation > 0.3 ? "over_limit" : deviation > 0.15 ? "warning" : "normal";

    // 成形进度：椭圆度随模具推进逐渐减小
    const ovality = +((1 - progressRatio) * 0.18).toFixed(3);

    return {
      dieIndex: idx,
      label: `模具 ${idx}`,
      xPos: curX,
      yPos: curY,
      angleOffset: curAngle,
      standard: { xPos: stdX, yPos: stdY, angleOffset: 0 },
      deviation,
      status,
      crossSection: {
        outerRadius: r,
        wallThickness: params.thickness,
        ovality,
        ovalityAngle: (idx * 22) % 180,
      },
    };
  });
}

/** 生成 16 个模具的总览模拟数据（用于 die_status_overview） */
export function generateDieStatusOverview(totalDies = 16): DiePositionData[] {
  return generateDiePositions({ outerDiameter: 20, thickness: 2, totalDies });
}
