// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
//
// SPDX-License-Identifier: GPL-3.0-or-later

export interface ParsedArgs {
  command?: string;
  options: Record<string, string | boolean>;
  positional: string[];
}

export function parseArgs(args: string[]): ParsedArgs {
  const [, , command, ...rest] = args;
  const options: Record<string, string | boolean> = {};
  const positional: string[] = [];

  for (let i = 0; i < rest.length; i += 1) {
    const arg = rest[i];
    if (!arg) continue;

    if (arg.startsWith("--")) {
      const eqIndex = arg.indexOf("=", 2);
      let key: string;
      let value: string | undefined;
      if (eqIndex !== -1) {
        key = arg.slice(2, eqIndex);
        value = arg.slice(eqIndex + 1);
      } else {
        key = arg.slice(2);
      }
      if (!key) continue;
      if (value !== undefined) {
        options[key] = value;
      } else if (rest[i + 1] && !rest[i + 1]?.startsWith("-")) {
        options[key] = rest[i + 1] as string;
        i += 1;
      } else {
        options[key] = true;
      }
    } else if (arg.startsWith("-")) {
      const short = arg.slice(1);
      if (short === "u") {
        if (rest[i + 1] && !rest[i + 1]!.startsWith("-")) {
          options["uri"] = rest[i + 1] as string;
          i += 1;
        }
        // else: -u with no value — uri stays unset, command handler validates
      } else if (short === "f") {
        options["full"] = true;
      } else if (short === "v") {
        options["version"] = true;
      } else {
        options[short] = true;
      }
    } else {
      positional.push(arg);
    }
  }

  return { command, options, positional };
}
