import { ValidationError } from "./validation.ts";

export function parseArgs(argv: string[]): Map<string, string | true> {
  const result = new Map<string, string | true>();
  for (let index = 0; index < argv.length; index += 1) {
    const token = argv[index];
    if (!token?.startsWith("--")) throw new ValidationError(`Argument inattendu: ${token ?? ""}`);
    const name = token.slice(2);
    if (name === "require-signature") {
      result.set(name, true);
      continue;
    }
    const value = argv[index + 1];
    if (!value || value.startsWith("--")) throw new ValidationError(`Valeur absente pour --${name}`);
    if (result.has(name)) throw new ValidationError(`Argument répété: --${name}`);
    result.set(name, value);
    index += 1;
  }
  return result;
}

export function requiredArg(args: Map<string, string | true>, name: string): string {
  const value = args.get(name);
  if (typeof value !== "string") throw new ValidationError(`Argument requis: --${name}`);
  return value;
}

export function optionalArg(args: Map<string, string | true>, name: string): string | undefined {
  const value = args.get(name);
  return typeof value === "string" ? value : undefined;
}

export function assertKnownArgs(args: Map<string, string | true>, allowed: readonly string[]): void {
  const allowedSet = new Set(allowed);
  const unknown = [...args.keys()].filter((entry) => !allowedSet.has(entry));
  if (unknown.length > 0) throw new ValidationError(`Arguments inconnus: ${unknown.join(", ")}`);
}

export function reportCliError(error: unknown): never {
  const message = error instanceof Error ? error.message : String(error);
  process.stderr.write(`Erreur: ${message}\n`);
  process.exit(1);
}
