import type { AxelQuoteCliInput } from "@/lib/axel/client";

function readFlagValue(argv: string[], flag: string): string | undefined {
  const idx = argv.indexOf(flag);
  if (idx < 0) {
    return undefined;
  }
  return argv[idx + 1];
}

function readNumberFlag(argv: string[], flag: string): number | undefined {
  const raw = readFlagValue(argv, flag);
  if (raw == null) {
    return undefined;
  }
  const n = Number(raw);
  return Number.isFinite(n) ? n : undefined;
}

export function parseQuoteCliArgs(argv: string[]): AxelQuoteCliInput {
  const origin = readFlagValue(argv, "--origin");
  const dest = readFlagValue(argv, "--dest");
  if (!origin?.trim() || !dest?.trim()) {
    throw new Error(
      "用法: npm run quote -- --origin \"提货地址\" --dest \"派送地址\" --pallets 2 --weight 500 [--length 48 --width 40 --height 45]",
    );
  }

  const pallets = readNumberFlag(argv, "--pallets");
  const weightLb = readNumberFlag(argv, "--weight");
  if (pallets == null || pallets <= 0) {
    throw new Error("--pallets 须为正整数");
  }
  if (weightLb == null || weightLb <= 0) {
    throw new Error("--weight 须为正数（磅）");
  }

  const lengthIn = readNumberFlag(argv, "--length");
  const widthIn = readNumberFlag(argv, "--width");
  const heightIn = readNumberFlag(argv, "--height");
  const storageStatePath = readFlagValue(argv, "--storage");

  return {
    origin: origin.trim(),
    dest: dest.trim(),
    pallets: Math.floor(pallets),
    weightLb,
    lengthIn,
    widthIn,
    heightIn,
    storageStatePath,
  };
}
