(() => {
  const STORAGE_KEY = "mmw.qianchuanAgent.commandPending.v1";
  const TTL_MS = 5 * 60 * 1000;
  const DECISION_PATTERN = /^(?:千川\s*)?(确认|取消)\s*[:：]?\s*([A-Za-z0-9]{4,12})$/i;

  function parseDecision(text) {
    const match = DECISION_PATTERN.exec(String(text || "").replace(/\s+/g, " ").trim());
    if (!match) return null;
    return { kind: match[1] === "确认" ? "confirm" : "cancel", code: match[2].toUpperCase() };
  }

  function createCode() {
    const bytes = new Uint32Array(1);
    crypto.getRandomValues(bytes);
    return String(100000 + (bytes[0] % 900000));
  }

  function read(storage = localStorage, now = Date.now()) {
    let entries = [];
    try {
      entries = JSON.parse(storage.getItem(STORAGE_KEY) || "[]");
    } catch {}
    const fresh = (Array.isArray(entries) ? entries : []).filter((item) =>
      item && Number(now) - Number(item.createdAt || 0) < TTL_MS
    );
    if (fresh.length !== entries.length) write(storage, fresh);
    return fresh;
  }

  function write(storage, entries) {
    storage.setItem(STORAGE_KEY, JSON.stringify(entries.slice(-24)));
  }

  function save({ proposal, sourceId = "", accountKey = "", scope = "", scopeLabel = "" }, storage = localStorage, now = Date.now()) {
    const entries = read(storage, now);
    const existing = entries.find((item) =>
      (sourceId && item.sourceId === sourceId)
      || (item.proposal?.id && item.proposal.id === proposal?.id)
    );
    if (existing) return existing;
    let code = createCode();
    while (entries.some((item) => item.code === code)) code = createCode();
    const pending = {
      code,
      sourceId: String(sourceId || ""),
      accountKey: String(accountKey || ""),
      scope: String(scope || ""),
      scopeLabel: String(scopeLabel || ""),
      createdAt: Number(now),
      proposal: {
        id: String(proposal?.id || ""),
        kind: String(proposal?.kind || ""),
        payload: proposal?.payload && typeof proposal.payload === "object" ? proposal.payload : {}
      }
    };
    entries.push(pending);
    write(storage, entries);
    return pending;
  }

  function find(code, { accountKey = "", scope = "" } = {}, storage = localStorage, now = Date.now()) {
    const pending = read(storage, now).find((item) => item.code === String(code || "").toUpperCase());
    if (!pending) return { status: "missing", pending: null };
    if (pending.accountKey !== String(accountKey || "") || pending.scope !== String(scope || "")) {
      return { status: "wrong_scope", pending };
    }
    return { status: "found", pending };
  }

  function claimDecision(
    code,
    { accountKey = "", scope = "" } = {},
    decisionKind = "confirm",
    sourceId = "",
    storage = localStorage,
    now = Date.now()
  ) {
    const entries = read(storage, now);
    const pending = entries.find((item) => item.code === String(code || "").toUpperCase());
    if (!pending) return { status: "missing", pending: null };
    if (pending.accountKey !== String(accountKey || "") || pending.scope !== String(scope || "")) {
      return { status: "wrong_scope", pending };
    }
    if (pending.decisionStatus) return { status: "duplicate", pending };
    pending.decisionStatus = "processing";
    pending.decisionKind = decisionKind === "cancel" ? "cancel" : "confirm";
    pending.decisionSourceId = String(sourceId || "").slice(0, 120);
    pending.decisionAt = Number(now);
    write(storage, entries);
    return { status: "claimed", pending };
  }

  function finishDecision(code, outcome = "completed", storage = localStorage, now = Date.now()) {
    const entries = read(storage, now);
    const pending = entries.find((item) => item.code === String(code || "").toUpperCase());
    if (!pending || !pending.decisionStatus) return false;
    pending.decisionStatus = outcome === "failed" ? "failed" : "completed";
    pending.handledAt = Number(now);
    write(storage, entries);
    return true;
  }

  function remove(code, storage = localStorage, now = Date.now()) {
    write(storage, read(storage, now).filter((item) => item.code !== String(code || "").toUpperCase()));
  }

  function commandHint(code) {
    return `5 分钟内只需发送一次“确认 ${code}”执行，或发送“取消 ${code}”撤销；重复发送不会重复执行。`;
  }

  const api = { TTL_MS, parseDecision, save, find, claimDecision, finishDecision, remove, read, commandHint };
  if (typeof window !== "undefined") window.MMWQianchuanCommandConfirmation = api;
  if (typeof module !== "undefined" && module.exports) module.exports = api;
})();
