import { emitApi } from "../core/http.js";
import { parseOptions, requiredNumber, requiredString } from "../core/options.js";
import { addMinutesPreservingOffset, parseTime } from "../core/time.js";
import type { HandlerMap, RuntimeContext } from "../core/types.js";

function simulationRun(ctx: RuntimeContext, argv: string[]): Promise<void> {
  const { values } = parseOptions(argv, { duration: "integer" });
  const start = parseTime(requiredString(values, "start-time"), "--start-time");
  const duration = requiredNumber(values, "duration");
  const end = addMinutesPreservingOffset(start, duration);
  return emitApi(
    ctx,
    "触发模拟成功",
    { method: "POST", path: "/simulation-runs", body: { start_time: start.replace(/\.\d+/, ""), duration }, requireProject: true },
    [
      `tjwater-cli data timeseries realtime links --start-time ${start} --end-time ${end}`,
      `tjwater-cli data timeseries realtime nodes --start-time ${start} --end-time ${end}`,
    ],
  );
}

export const simulationHandlers: HandlerMap = {
  "simulation run": simulationRun,
};
