// Cron edit command registration and patch construction for existing jobs.
import {
  normalizeOptionalLowercaseString,
  normalizeOptionalString,
} from "@openclaw/normalization-core/string-coerce";
import type { Command } from "commander";
import type { CronJob } from "../../cron/types.js";
import { danger } from "../../globals.js";
import { parseStrictPositiveInteger } from "../../infra/parse-finite-number.js";
import { sanitizeAgentId } from "../../routing/session-key.js";
import { defaultRuntime } from "../../runtime.js";
import { addGatewayClientOptions, callGatewayFromCli } from "../gateway-rpc.js";
import {
  applyExistingCronSchedulePatch,
  resolveCronEditScheduleRequest,
} from "./schedule-options.js";
import {
  getCronChannelOptions,
  parseCronCommandArgv,
  parseCronCommandEnv,
  parseCronToolsAllow,
  parseDurationMs,
  warnIfCronSchedulerDisabled,
} from "./shared.js";
import { normalizeCronSessionTargetOption, parseCronThreadIdOption } from "./thread-id-shared.js";

const CRON_EDIT_LOOKUP_PAGE_SIZE = 200;
const CRON_EDIT_LOOKUP_MAX_PAGES = 50;

const assignIf = (
  target: Record<string, unknown>,
  key: string,
  value: unknown,
  shouldAssign: boolean,
) => {
  if (shouldAssign) {
    target[key] = value;
  }
};

async function loadCronJobForEditSchedulePatch(
  opts: Record<string, unknown>,
  id: string,
): Promise<CronJob | undefined> {
  // Schedule patches need the existing job; page defensively because gateway stores can be large.
  let offset = 0;
  for (let page = 0; page < CRON_EDIT_LOOKUP_MAX_PAGES; page += 1) {
    const listed = (await callGatewayFromCli("cron.list", opts, {
      includeDisabled: true,
      limit: CRON_EDIT_LOOKUP_PAGE_SIZE,
      offset,
    })) as { jobs?: CronJob[]; hasMore?: boolean; nextOffset?: number | null } | null;
    const existing = (listed?.jobs ?? []).find((job) => job.id === id);
    if (existing) {
      return existing;
    }
    if (!listed?.hasMore || typeof listed.nextOffset !== "number") {
      return undefined;
    }
    if (listed.nextOffset <= offset) {
      throw new Error("cron.list pagination did not advance while looking up cron job");
    }
    offset = listed.nextOffset;
  }
  throw new Error("cron.list pagination exceeded maximum pages while looking up cron job");
}

async function readCronJobForEdit(opts: Record<string, unknown>, id: string): Promise<CronJob> {
  return (await callGatewayFromCli("cron.get", opts, { id })) as CronJob;
}

export function registerCronEditCommand(cron: Command) {
  addGatewayClientOptions(
    cron
      .command("edit")
      .description("Edit a cron job (patch fields)")
      .argument("<id>", "Job id")
      .option("--name <name>", "Set name")
      .option("--description <text>", "Set description")
      .option("--enable", "Enable job", false)
      .option("--disable", "Disable job", false)
      .option("--delete-after-run", "Delete one-shot job after it succeeds", false)
      .option("--keep-after-run", "Keep one-shot job after it succeeds", false)
      .option("--session <target>", "Session target (main|isolated)")
      .option("--agent <id>", "Set agent id")
      .option("--clear-agent", "Unset agent and use default", false)
      .option("--session-key <key>", "Set session key for job routing")
      .option("--clear-session-key", "Unset session key", false)
      .option("--wake <mode>", "Wake mode (now|next-heartbeat)")
      .option("--at <when>", "Set one-shot time (ISO) or duration like 20m")
      .option("--every <duration>", "Set interval duration like 10m")
      .option("--cron <expr>", "Set cron expression")
      .option(
        "--tz <iana>",
        "Timezone for cron expressions (IANA; cron default: Gateway host local timezone)",
      )
      .option("--stagger <duration>", "Cron stagger window (e.g. 30s, 5m)")
      .option("--exact", "Disable cron staggering (set stagger to 0)")
      .option("--system-event <text>", "Set systemEvent payload")
      .option("--message <text>", "Set agentTurn payload message")
      .option("--command <shell>", "Set command payload run as sh -lc <shell> on the Gateway")
      .option("--command-argv <json>", "Set command payload argv as JSON array of strings")
      .option("--command-cwd <path>", "Set command payload working directory")
      .option(
        "--command-env <KEY=VALUE>",
        "Set command payload environment overrides (repeatable)",
        (value: string, previous: string[] | undefined) => [...(previous ?? []), value],
      )
      .option("--command-input <text>", "Set command payload stdin")
      .option(
        "--thinking <level>",
        "Thinking level for agent jobs (off|minimal|low|medium|high|xhigh)",
      )
      .option("--model <model>", "Model override for agent jobs")
      .option("--timeout-seconds <n>", "Timeout seconds for agent or command jobs")
      .option("--no-output-timeout-seconds <n>", "No-output timeout seconds for command jobs")
      .option("--output-max-bytes <n>", "Maximum captured stdout/stderr bytes for command jobs")
      .option("--light-context", "Enable lightweight bootstrap context for agent jobs")
      .option("--no-light-context", "Disable lightweight bootstrap context for agent jobs")
      .option("--tools <list>", "Tool allow-list (e.g. exec,read,write or exec read write)")
      .option("--clear-tools", "Remove tool allow-list (use all tools)", false)
      .option("--announce", "Fallback-deliver final text to a chat")
      .option("--deliver", "Deprecated (use --announce). Fallback-delivers final text to a chat.")
      .option("--no-deliver", "Disable runner fallback delivery")
      .option("--webhook <url>", "POST the finished payload to a webhook URL")
      .option("--channel <channel>", `Delivery channel (${getCronChannelOptions()})`)
      .option(
        "--to <dest>",
        "Delivery destination (E.164, Telegram chatId, or Discord channel/user)",
      )
      .option("--thread-id <id>", "Telegram forum topic thread id")
      .option("--account <id>", "Channel account id for delivery (multi-account setups)")
      .option(
        "--best-effort-deliver",
        "Do not fail job if delivery fails (also implies --announce when used alone)",
      )
      .option("--no-best-effort-deliver", "Fail job when delivery fails")
      .option("--failure-alert", "Enable failure alerts for this job")
      .option("--no-failure-alert", "Disable failure alerts for this job")
      .option("--failure-alert-after <n>", "Alert after N consecutive job errors")
      .option(
        "--failure-alert-channel <channel>",
        `Failure alert channel (${getCronChannelOptions()})`,
      )
      .option("--failure-alert-to <dest>", "Failure alert destination")
      .option("--failure-alert-cooldown <duration>", "Minimum time between alerts (e.g. 1h, 30m)")
      .option("--failure-alert-include-skipped", "Count consecutive skipped runs toward alerts")
      .option("--failure-alert-exclude-skipped", "Alert only on execution errors")
      .option("--failure-alert-mode <mode>", "Failure alert delivery mode (announce or webhook)")
      .option(
        "--failure-alert-account-id <id>",
        "Account ID for failure alert channel (multi-account setups)",
      )
      .action(async (id, opts) => {
        try {
          const sessionTarget =
            typeof opts.session === "string"
              ? normalizeCronSessionTargetOption(opts.session)
              : undefined;
          if (typeof opts.session === "string" && !sessionTarget) {
            throw new Error("--session must be main, isolated, current, or session:<id>");
          }
          if (sessionTarget === "main" && (opts.message || opts.command || opts.commandArgv)) {
            throw new Error(
              "Main jobs cannot use --message or --command; use --system-event or --session isolated.",
            );
          }
          if (
            (sessionTarget === "isolated" ||
              sessionTarget === "current" ||
              sessionTarget?.startsWith("session:")) &&
            opts.systemEvent
          ) {
            throw new Error(
              "Isolated jobs cannot use --system-event; use --message, --command, or --session main.",
            );
          }
          const hasWebhookDelivery = typeof opts.webhook === "string";
          const deliveryModeFlagCount = [
            Boolean(opts.announce),
            typeof opts.deliver === "boolean",
            hasWebhookDelivery,
          ].filter(Boolean).length;
          if (deliveryModeFlagCount > 1) {
            throw new Error("Choose at most one of --announce, --no-deliver, or --webhook.");
          }
          const patch: Record<string, unknown> = {};
          if (typeof opts.name === "string") {
            patch.name = opts.name;
          }
          if (typeof opts.description === "string") {
            patch.description = opts.description;
          }
          if (opts.enable && opts.disable) {
            throw new Error("Choose --enable or --disable, not both");
          }
          if (opts.enable) {
            patch.enabled = true;
          }
          if (opts.disable) {
            patch.enabled = false;
          }
          if (opts.deleteAfterRun && opts.keepAfterRun) {
            throw new Error("Choose --delete-after-run or --keep-after-run, not both");
          }
          if (opts.deleteAfterRun) {
            patch.deleteAfterRun = true;
          }
          if (opts.keepAfterRun) {
            patch.deleteAfterRun = false;
          }
          if (typeof opts.session === "string") {
            patch.sessionTarget = sessionTarget;
          }
          if (typeof opts.wake === "string") {
            const wakeMode = opts.wake.trim();
            if (wakeMode !== "now" && wakeMode !== "next-heartbeat") {
              throw new Error("--wake must be now or next-heartbeat");
            }
            patch.wakeMode = wakeMode;
          }
          if (opts.agent && opts.clearAgent) {
            throw new Error("Use --agent or --clear-agent, not both");
          }
          if (typeof opts.agent === "string" && opts.agent.trim()) {
            patch.agentId = sanitizeAgentId(opts.agent.trim());
          }
          if (opts.clearAgent) {
            patch.agentId = null;
          }
          if (opts.sessionKey && opts.clearSessionKey) {
            throw new Error("Use --session-key or --clear-session-key, not both");
          }
          if (typeof opts.sessionKey === "string" && opts.sessionKey.trim()) {
            patch.sessionKey = opts.sessionKey.trim();
          }
          if (opts.clearSessionKey) {
            patch.sessionKey = null;
          }

          const scheduleRequest = resolveCronEditScheduleRequest({
            at: opts.at,
            cron: opts.cron,
            every: opts.every,
            exact: opts.exact,
            stagger: opts.stagger,
            tz: opts.tz,
          });
          if (scheduleRequest.kind === "direct") {
            if (
              scheduleRequest.schedule.kind === "cron" &&
              scheduleRequest.schedule.tz === undefined
            ) {
              const existing = await readCronJobForEdit(opts, String(id));
              patch.schedule =
                existing.schedule.kind === "cron" && existing.schedule.tz !== undefined
                  ? { ...scheduleRequest.schedule, tz: existing.schedule.tz }
                  : scheduleRequest.schedule;
            } else {
              patch.schedule = scheduleRequest.schedule;
            }
          } else if (scheduleRequest.kind === "patch-existing-cron") {
            const existing = await loadCronJobForEditSchedulePatch(opts, String(id));
            if (!existing) {
              throw new Error(`unknown cron job id: ${id}`);
            }
            patch.schedule = applyExistingCronSchedulePatch(existing.schedule, scheduleRequest);
          }

          const hasSystemEventPatch = typeof opts.systemEvent === "string";
          const commandShell = normalizeOptionalString(opts.command);
          const commandArgv = parseCronCommandArgv(opts.commandArgv);
          if (commandShell && commandArgv) {
            throw new Error(
              "Pass command payload either with --command or --command-argv, not both.",
            );
          }
          const model = normalizeOptionalString(opts.model);
          const thinking = normalizeOptionalString(opts.thinking);
          const toolsAllow = parseCronToolsAllow(opts.tools);
          const rawTimeoutSeconds =
            opts.timeoutSeconds === undefined ? undefined : String(opts.timeoutSeconds).trim();
          if (rawTimeoutSeconds !== undefined && !/^\d+$/u.test(rawTimeoutSeconds)) {
            throw new Error("Invalid --timeout-seconds (must be a positive integer).");
          }
          const timeoutSeconds =
            rawTimeoutSeconds === undefined ? undefined : Number(rawTimeoutSeconds);
          const hasTimeoutSeconds =
            typeof timeoutSeconds === "number" &&
            Number.isSafeInteger(timeoutSeconds) &&
            timeoutSeconds > 0;
          if (rawTimeoutSeconds !== undefined && !hasTimeoutSeconds) {
            throw new Error("Invalid --timeout-seconds (must be a positive integer).");
          }
          const rawNoOutputTimeoutSeconds =
            opts.noOutputTimeoutSeconds ??
            (typeof opts.outputTimeoutSeconds === "string" ||
            typeof opts.outputTimeoutSeconds === "number"
              ? opts.outputTimeoutSeconds
              : undefined);
          const noOutputTimeoutSeconds = parseStrictPositiveInteger(rawNoOutputTimeoutSeconds);
          if (rawNoOutputTimeoutSeconds !== undefined && noOutputTimeoutSeconds === undefined) {
            throw new Error("Invalid --no-output-timeout-seconds (must be a positive integer).");
          }
          const outputMaxBytes = parseStrictPositiveInteger(opts.outputMaxBytes);
          if (opts.outputMaxBytes !== undefined && outputMaxBytes === undefined) {
            throw new Error("Invalid --output-max-bytes (must be a positive integer).");
          }
          const hasDeliveryModeFlag =
            opts.announce || typeof opts.deliver === "boolean" || hasWebhookDelivery;
          const threadId = parseCronThreadIdOption(opts.threadId);
          const hasDeliveryThreadId = typeof threadId === "number";
          const hasDeliveryTarget =
            typeof opts.channel === "string" || typeof opts.to === "string" || hasDeliveryThreadId;
          const hasDeliveryAccount = typeof opts.account === "string";
          const hasBestEffort = typeof opts.bestEffortDeliver === "boolean";
          if (hasWebhookDelivery && (hasDeliveryTarget || hasDeliveryAccount)) {
            throw new Error("--webhook cannot be combined with chat delivery options.");
          }
          const hasCommandSpecificPayloadField =
            Boolean(commandShell) ||
            Boolean(commandArgv) ||
            typeof opts.commandCwd === "string" ||
            typeof opts.commandInput === "string" ||
            opts.commandEnv !== undefined ||
            noOutputTimeoutSeconds !== undefined ||
            outputMaxBytes !== undefined;
          let timeoutOnlyPayloadKind: "agentTurn" | "command" | undefined;
          if (
            hasTimeoutSeconds &&
            !hasCommandSpecificPayloadField &&
            typeof opts.message !== "string" &&
            !model &&
            !thinking &&
            typeof opts.lightContext !== "boolean" &&
            typeof opts.tools !== "string" &&
            !Array.isArray(opts.tools) &&
            !opts.clearTools
          ) {
            const existing = await loadCronJobForEditSchedulePatch(opts, String(id));
            timeoutOnlyPayloadKind = existing?.payload.kind === "command" ? "command" : "agentTurn";
          }
          const hasAgentTurnPayloadField =
            typeof opts.message === "string" ||
            Boolean(model) ||
            Boolean(thinking) ||
            (hasTimeoutSeconds &&
              !hasCommandSpecificPayloadField &&
              timeoutOnlyPayloadKind !== "command") ||
            typeof opts.lightContext === "boolean" ||
            typeof opts.tools === "string" ||
            Array.isArray(opts.tools) ||
            opts.clearTools;
          const hasCommandPayloadField =
            hasCommandSpecificPayloadField ||
            (hasTimeoutSeconds &&
              (hasCommandSpecificPayloadField || timeoutOnlyPayloadKind === "command"));
          const hasAgentTurnPatch = hasAgentTurnPayloadField;
          const hasCommandPatch = hasCommandPayloadField;
          if (
            [hasSystemEventPatch, hasAgentTurnPatch, hasCommandPatch].filter(Boolean).length > 1
          ) {
            throw new Error("Choose at most one payload change");
          }
          if (hasSystemEventPatch) {
            patch.payload = {
              kind: "systemEvent",
              text: String(opts.systemEvent),
            };
          } else if (hasAgentTurnPatch) {
            const payload: Record<string, unknown> = { kind: "agentTurn" };
            assignIf(payload, "message", String(opts.message), typeof opts.message === "string");
            assignIf(payload, "model", model, Boolean(model));
            assignIf(payload, "thinking", thinking, Boolean(thinking));
            assignIf(payload, "timeoutSeconds", timeoutSeconds, hasTimeoutSeconds);
            assignIf(
              payload,
              "lightContext",
              opts.lightContext,
              typeof opts.lightContext === "boolean",
            );
            if (opts.clearTools) {
              payload.toolsAllow = null;
            } else if (toolsAllow) {
              payload.toolsAllow = toolsAllow;
            }
            patch.payload = payload;
          } else if (hasCommandPatch) {
            const payload: Record<string, unknown> = { kind: "command" };
            assignIf(payload, "argv", commandArgv, Boolean(commandArgv));
            assignIf(payload, "argv", ["sh", "-lc", commandShell], Boolean(commandShell));
            assignIf(
              payload,
              "cwd",
              normalizeOptionalString(opts.commandCwd),
              typeof opts.commandCwd === "string",
            );
            assignIf(
              payload,
              "env",
              parseCronCommandEnv(opts.commandEnv),
              opts.commandEnv !== undefined,
            );
            assignIf(payload, "input", opts.commandInput, typeof opts.commandInput === "string");
            assignIf(payload, "timeoutSeconds", timeoutSeconds, hasTimeoutSeconds);
            assignIf(
              payload,
              "noOutputTimeoutSeconds",
              noOutputTimeoutSeconds,
              noOutputTimeoutSeconds !== undefined,
            );
            assignIf(payload, "outputMaxBytes", outputMaxBytes, outputMaxBytes !== undefined);
            patch.payload = payload;
          }

          if (hasDeliveryModeFlag || hasDeliveryTarget || hasDeliveryAccount || hasBestEffort) {
            const delivery: Record<string, unknown> = {};
            if (hasDeliveryModeFlag) {
              delivery.mode = hasWebhookDelivery
                ? "webhook"
                : opts.announce || opts.deliver === true
                  ? "announce"
                  : "none";
            } else if (
              opts.bestEffortDeliver === true ||
              ((hasAgentTurnPayloadField || hasCommandPayloadField) && hasBestEffort)
            ) {
              // Back-compat: best-effort true and payload edits historically implied announce mode.
              delivery.mode = "announce";
            }
            if (typeof opts.channel === "string") {
              const channel = opts.channel.trim();
              delivery.channel = channel ? channel : undefined;
            }
            if (hasWebhookDelivery) {
              const webhook = normalizeOptionalString(opts.webhook) ?? "";
              delivery.to = webhook ? webhook : undefined;
            } else if (typeof opts.to === "string") {
              const to = opts.to.trim();
              delivery.to = to ? to : undefined;
            }
            if (hasDeliveryThreadId) {
              delivery.threadId = threadId;
            }
            if (typeof opts.account === "string") {
              const account = opts.account.trim();
              delivery.accountId = account ? account : undefined;
            }
            if (typeof opts.bestEffortDeliver === "boolean") {
              delivery.bestEffort = opts.bestEffortDeliver;
            }
            patch.delivery = delivery;
          }

          const hasFailureAlertAfter = typeof opts.failureAlertAfter === "string";
          const hasFailureAlertChannel = typeof opts.failureAlertChannel === "string";
          const hasFailureAlertTo = typeof opts.failureAlertTo === "string";
          const hasFailureAlertCooldown = typeof opts.failureAlertCooldown === "string";
          const hasFailureAlertIncludeSkipped =
            typeof opts.failureAlertIncludeSkipped === "boolean";
          const hasFailureAlertExcludeSkipped =
            typeof opts.failureAlertExcludeSkipped === "boolean";
          const hasFailureAlertMode = typeof opts.failureAlertMode === "string";
          const hasFailureAlertAccountId = typeof opts.failureAlertAccountId === "string";
          if (hasFailureAlertIncludeSkipped && hasFailureAlertExcludeSkipped) {
            throw new Error(
              "Use either --failure-alert-include-skipped or --failure-alert-exclude-skipped.",
            );
          }
          const hasFailureAlertFields =
            hasFailureAlertAfter ||
            hasFailureAlertChannel ||
            hasFailureAlertTo ||
            hasFailureAlertCooldown ||
            hasFailureAlertIncludeSkipped ||
            hasFailureAlertExcludeSkipped ||
            hasFailureAlertMode ||
            hasFailureAlertAccountId;
          const failureAlertFlag =
            typeof opts.failureAlert === "boolean" ? opts.failureAlert : undefined;
          if (failureAlertFlag === false && hasFailureAlertFields) {
            throw new Error("Use --no-failure-alert alone (without failure-alert-* options).");
          }
          if (failureAlertFlag === false) {
            patch.failureAlert = false;
          } else if (failureAlertFlag === true || hasFailureAlertFields) {
            const failureAlert: Record<string, unknown> = {};
            if (hasFailureAlertAfter) {
              const after = parseStrictPositiveInteger(opts.failureAlertAfter);
              if (after === undefined) {
                throw new Error("Invalid --failure-alert-after (must be a positive integer).");
              }
              failureAlert.after = after;
            }
            if (hasFailureAlertChannel) {
              failureAlert.channel = normalizeOptionalLowercaseString(opts.failureAlertChannel);
            }
            if (hasFailureAlertTo) {
              const to = normalizeOptionalString(opts.failureAlertTo) ?? "";
              failureAlert.to = to ? to : undefined;
            }
            if (hasFailureAlertCooldown) {
              const cooldownMs = parseDurationMs(String(opts.failureAlertCooldown));
              if (!cooldownMs && cooldownMs !== 0) {
                throw new Error("Invalid --failure-alert-cooldown.");
              }
              failureAlert.cooldownMs = cooldownMs;
            }
            if (hasFailureAlertIncludeSkipped || hasFailureAlertExcludeSkipped) {
              failureAlert.includeSkipped = hasFailureAlertIncludeSkipped;
            }
            if (hasFailureAlertMode) {
              const mode = normalizeOptionalLowercaseString(opts.failureAlertMode);
              if (mode !== "announce" && mode !== "webhook") {
                throw new Error("Invalid --failure-alert-mode (must be 'announce' or 'webhook').");
              }
              failureAlert.mode = mode;
            }
            if (hasFailureAlertAccountId) {
              const accountId = normalizeOptionalString(opts.failureAlertAccountId) ?? "";
              failureAlert.accountId = accountId ? accountId : undefined;
            }
            patch.failureAlert = failureAlert;
          }

          const res = await callGatewayFromCli("cron.update", opts, {
            id,
            patch,
          });
          defaultRuntime.writeJson(res);
          await warnIfCronSchedulerDisabled(opts);
        } catch (err) {
          defaultRuntime.error(danger(String(err)));
          defaultRuntime.exit(1);
        }
      }),
  );
}
