import { CliError } from "../core/errors.js";
import { emitApi } from "../core/http.js";
import { optionalString, parseOptions, requiredString, validateChoice } from "../core/options.js";
import type { HandlerMap, RuntimeContext } from "../core/types.js";

type ComponentKind = "time" | "energy" | "pump-energy" | "network";

function componentOption(ctx: RuntimeContext, argv: string[], schema: boolean): Promise<void> {
  const { values } = parseOptions(argv);
  const kind = validateChoice(requiredString(values, "kind"), ["time", "energy", "pump-energy", "network"] as const, "--kind");
  const routes: Record<`${ComponentKind}:${boolean}`, string> = {
    "time:true": "/network-schemas/time",
    "time:false": "/network-options/time",
    "energy:true": "/network-schemas/energy",
    "energy:false": "/network-options/energy",
    "pump-energy:true": "/network-schemas/pump-energy",
    "pump-energy:false": "/network-options/pump-energy",
    "network:true": "/network-schemas/option",
    "network:false": "/network-options",
  };
  const params: Record<string, unknown> = {};
  const pump = optionalString(values, "pump");
  if (kind === "pump-energy") {
    if (!schema && !pump) throw new CliError("CLI 参数错误", "PUMP_REQUIRED", "--pump is required when --kind pump-energy", 2);
    if (pump) params.pump = pump;
  }
  return emitApi(ctx, schema ? "读取选项 schema 成功" : "读取选项属性成功", { method: "GET", path: routes[`${kind}:${schema}`], params, requireProject: true });
}

export const componentHandlers: HandlerMap = {
  "component option schema": (ctx, argv) => componentOption(ctx, argv, true),
  "component option get": (ctx, argv) => componentOption(ctx, argv, false),
};
