import type { ParsedArgs } from "../../args";
import { callDaemon } from "../../client";
import { createUsageError } from "../../errors";
import { DEFAULT_TARGET_CREATION_TRANSPORT_TIMEOUT_MS } from "../../transport-timeouts";

function parseTargetNewArgs(rawArgs: string[]): { sessionId?: string; url?: string } {
  const parsed: { sessionId?: string; url?: string } = {};
  for (let i = 0; i < rawArgs.length; i += 1) {
    const arg = rawArgs[i];
    if (arg === "--session-id") {
      const value = rawArgs[i + 1];
      if (!value) throw createUsageError("Missing value for --session-id");
      parsed.sessionId = value;
      i += 1;
      continue;
    }
    if (arg?.startsWith("--session-id=")) {
      parsed.sessionId = arg.split("=", 2)[1];
      continue;
    }
    if (arg === "--url") {
      const value = rawArgs[i + 1];
      if (!value) throw createUsageError("Missing value for --url");
      parsed.url = value;
      i += 1;
      continue;
    }
    if (arg?.startsWith("--url=")) {
      parsed.url = arg.split("=", 2)[1];
      continue;
    }
  }
  return parsed;
}

export async function runTargetNew(args: ParsedArgs) {
  const { sessionId, url } = parseTargetNewArgs(args.rawArgs);
  if (!sessionId) throw createUsageError("Missing --session-id");
  const result = await callDaemon(
    "targets.new",
    { sessionId, url },
    { timeoutMs: DEFAULT_TARGET_CREATION_TRANSPORT_TIMEOUT_MS }
  );
  return { success: true, message: "Target created.", data: result };
}
