(() => {
  if (typeof window !== "undefined" && window.MMWQianchuanWorkflowRuntime) return;

  function createWorkflowRuntime(options) {
    const {
      workflowApi,
      dataReportApi,
      chromeApi,
      root,
      state,
      actionLabels,
      collectSnapshot,
      acquireLease,
      setBusy,
      normalizeProposal,
      executeProposal,
      checkPlanControlCooldown,
      postEvent,
      submitDataReport,
      submitNotification,
      isAgentEnabled,
      isFatalRuntimeError,
      onFatalRuntimeError,
      setAgentPhase,
      workerInstanceId,
      render
    } = options;
    const canRunAgent = typeof isAgentEnabled === "function" ? isAgentEnabled : () => false;
    const fatalRuntimeError = typeof isFatalRuntimeError === "function" ? isFatalRuntimeError : () => false;
    const reportFatalRuntimeError = typeof onFatalRuntimeError === "function" ? onFatalRuntimeError : () => {};
    const updateAgentPhase = typeof setAgentPhase === "function" ? setAgentPhase : () => {};
    const inspectPlanControlCooldown = typeof checkPlanControlCooldown === "function"
      ? checkPlanControlCooldown
      : async () => ({ allowed: false, message: "每计划 1 小时调控限制组件未加载，本次未执行。" });
    let lastBlockedFeedbackKey = "";
    let lastBlockedFeedbackAt = 0;
    let fatalRuntimeStopped = false;

    function handleFatalRuntimeError(error) {
      if (!fatalRuntimeError(error)) return false;
      if (!fatalRuntimeStopped) {
        fatalRuntimeStopped = true;
        reportFatalRuntimeError(error);
      }
      return true;
    }

    function normalizedError(error, fallback) {
      return error instanceof Error ? error : new Error(error?.message || String(error || fallback));
    }

    function readLastError(fallback) {
      try {
        const error = chromeApi.runtime.lastError;
        return error ? normalizedError(error, fallback) : null;
      } catch (error) {
        return normalizedError(error, fallback);
      }
    }

    function agentCanRun() {
      return canRunAgent() === true
        && state.pageContext?.supported === true
        && Boolean(state.accountKey)
        && Boolean(state.scope);
    }

    function storageKey() {
      return `mmw.qianchuanAgent.workflow.v1:${encodeURIComponent(state.accountKey)}:${encodeURIComponent(state.scope)}`;
    }

    function loadStore() {
      if (!state.accountKey || !state.scope) return Promise.resolve({});
      const key = storageKey();
      return new Promise((resolve, reject) => {
        try {
          chromeApi.storage.local.get(key, (values) => {
            const error = readLastError("规则模板读取失败");
            if (error) {
              handleFatalRuntimeError(error);
              reject(error);
            } else resolve(values?.[key] && typeof values[key] === "object" ? values[key] : {});
          });
        } catch (error) {
          const normalized = normalizedError(error, "规则模板读取失败");
          handleFatalRuntimeError(normalized);
          reject(normalized);
        }
      });
    }

    function saveStore() {
      if (!state.accountKey || !state.scope) return Promise.resolve();
      const key = storageKey();
      const value = {
        schemaVersion: workflowApi.SCHEMA_VERSION,
        config: workflowApi.normalizeConfig(state.workflowConfig),
        runtime: workflowApi.normalizeRuntime(state.workflowRuntime),
        records: state.activityRecords.slice(-50),
        updatedAt: Date.now()
      };
      return new Promise((resolve, reject) => {
        try {
          chromeApi.storage.local.set({ [key]: value }, () => {
            const error = readLastError("规则模板保存失败");
            if (error) {
              handleFatalRuntimeError(error);
              reject(error);
            } else resolve();
          });
        } catch (error) {
          const normalized = normalizedError(error, "规则模板保存失败");
          handleFatalRuntimeError(normalized);
          reject(normalized);
        }
      });
    }

    function field(name) {
      return root.querySelector(`[data-workflow='${name}']`);
    }

    function readDraft(settingNumber) {
      const number = (name) => Number(field(name)?.value);
      const planIds = [...(root.querySelectorAll?.("[data-workflow-plan-id]") || [])]
        .map((input) => String(input.value || "").trim())
        .filter(Boolean);
      return {
        ...state.workflowConfig,
        enabled: field("enabled")?.checked === true,
        executionMode: root.querySelector("input[name='mmw-qca-mode']:checked")?.value || "confirm",
        intervalMinutes: number("intervalMinutes"),
        targetMode: root.querySelector("input[name='mmw-qca-target-mode']:checked")?.value || "all",
        planId: planIds[0] || "",
        planIds,
        hourlySpendTarget: number("hourlySpendTarget"),
        spendOverPercent: number("spendOverPercent"),
        roiIncrease: number("roiIncrease"),
        coldStartEnabled: field("coldStartEnabled")?.checked === true,
        coldStartMaxDecrease: number("coldStartMaxDecrease"),
        coldStartHourlySpendBelow: number("coldStartHourlySpendBelow"),
        coldStartRoiDecrease: number("coldStartRoiDecrease"),
        pauseBelowNetRoi: number("pauseBelowNetRoi"),
        lowRoiCycles: number("lowRoiCycles"),
        minimumSpend: number("minimumSpend"),
        maxActionsPerDay: settingNumber("max_actions_per_day"),
        notifications: {
          balanceEnabled: field("balanceEnabled")?.checked === true,
          balanceBelow: number("balanceBelow"),
          revenueRiseEnabled: field("revenueRiseEnabled")?.checked === true,
          revenueRisePercent: number("revenueRisePercent"),
          netRoiEnabled: field("netRoiEnabled")?.checked === true,
          netRoiBelow: number("netRoiBelow")
        },
        dataReport: {
          enabled: field("dataReportEnabled")?.checked === true,
          intervalMinutes: number("dataReportIntervalMinutes"),
          includeDashboard: field("dataReportDashboard")?.checked === true,
          includePlans: field("dataReportPlans")?.checked === true,
          deliveryMode: field("deliveryModePerAccount")?.checked === true ? "per_account" : "aggregate"
        }
      };
    }

    function compactText(value) {
      return String(value || "")
        .replace(/千川账户[^\n]*\n/g, "")
        .replace(/【千川 Agent[^】]*】/g, "")
        .replace(/\s+/g, " ")
        .trim()
        .slice(0, 360);
    }

    function mergeRecords(local, remote) {
      const values = [...(Array.isArray(local) ? local : []), ...(Array.isArray(remote) ? remote : [])]
        .filter((item) => item && item.text);
      const seen = new Set();
      return values.filter((item) => {
        const key = item.id || `${item.createdAt}:${item.text}`;
        if (seen.has(key)) return false;
        seen.add(key);
        return true;
      }).sort((left, right) => Number(left.createdAt || 0) - Number(right.createdAt || 0)).slice(-50);
    }

    async function addRecord(text, level = "info") {
      const value = compactText(text);
      if (!value) return;
      state.activityRecords = mergeRecords(state.activityRecords, [{
        id: `workflow-log-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
        createdAt: Date.now(),
        level: ["info", "success", "warning", "error", "pending"].includes(level) ? level : "info",
        text: value
      }]);
      await saveStore();
    }

    async function deliverNotification(notification) {
      if (!agentCanRun()) return;
      const message = `【千川 Agent 提醒】\n${String(notification?.message || "").slice(0, 300)}`;
      await addRecord(notification?.message || "提醒已触发", "warning");
      if (!agentCanRun()) return;
      try {
        await submitNotification({
          eventId: `qcn-${Date.now()}-${String(notification?.code || "alert").slice(0, 40)}`,
          workerInstanceId,
          accountKey: state.accountKey,
          accountName: state.accountName,
          scope: state.scope,
          message,
          channels: { weixin: false, feishu: false }
        });
        await addRecord("提醒已提交客户端通知队列", "success");
      } catch (error) {
        if (handleFatalRuntimeError(error)) return;
        await addRecord(`通知未入队 · ${String(error?.message || "发送失败").slice(0, 180)}`, "error");
      }
    }

    async function runDataReport(force = false) {
      if (!dataReportApi?.buildReport || typeof submitDataReport !== "function") return;
      const config = workflowApi.normalizeConfig(state.workflowConfig);
      if (!agentCanRun() || !config.dataReport.enabled || state.busy || state.remoteCommandBusy) return;
      const now = Date.now();
      if (!force && (now < Number(state.workflowRuntime?.dataReportRetryAt || 0)
        || !dataReportApi.isDue(state.workflowRuntime?.lastDataReportAt, config.dataReport.intervalMinutes, now))) return;
      updateAgentPhase("observing", "正在采集定时数据通知");
      try {
        const snapshot = collectSnapshot("全部计划");
        if (!agentCanRun()) return;
        const report = dataReportApi.buildReport({
          config,
          snapshot,
          accountKey: state.accountKey,
          accountName: state.accountName,
          scope: state.scope,
          workerInstanceId,
          now,
          randomUUID: () => globalThis.crypto?.randomUUID?.() || ""
        });
        if (!agentCanRun()) return;
        const response = await submitDataReport(report);
        if (!agentCanRun()) return;
        state.workflowRuntime.lastDataReportAt = now;
        state.workflowRuntime.dataReportRetryAt = 0;
        await addRecord(
          `数据通知已提交客户端 · ${config.targetMode === "all" ? `${report.plans.length} 个计划` : `${config.planIds.length} 个指定计划`} · ${response?.deliveryMode === "aggregate" ? "等待多账户汇总" : "按账户排队"}`,
          "success"
        );
        await saveStore();
        updateAgentPhase("monitoring", "盯盘运行中");
      } catch (error) {
        if (handleFatalRuntimeError(error)) return;
        state.workflowRuntime.dataReportRetryAt = now + 60_000;
        await addRecord(`数据通知等待重试 · ${String(error?.message || "当前数据不可用").slice(0, 180)}`, "warning");
        await saveStore().catch(() => null);
        updateAgentPhase(agentCanRun() ? "attention" : "off", error?.message || "数据通知等待处理");
      }
    }

    async function run(force = false) {
      const config = workflowApi.normalizeConfig(state.workflowConfig);
      if (!agentCanRun() || !config.enabled || state.busy || state.remoteCommandBusy
        || document.visibilityState === "hidden") return;
      if (!force && !workflowApi.isDue(state.workflowRuntime?.lastRunAt, config.intervalMinutes)) return;
      if (!acquireLease()) return;
      setBusy(true);
      updateAgentPhase("observing", "正在读取当前计划数据");
      try {
        const runtime = force ? { ...state.workflowRuntime, lastRunAt: 0 } : state.workflowRuntime;
        const snapshot = collectSnapshot("全部计划");
        if (!agentCanRun()) return;
        const evaluation = workflowApi.evaluate(config, runtime, snapshot, Date.now());
        state.workflowRuntime = evaluation.runtime;
        if (["not_due", "disabled"].includes(evaluation.status)) {
          updateAgentPhase("monitoring", "盯盘运行中");
          return;
        }
        const feedbackKey = `${evaluation.code || evaluation.status}:${evaluation.feedback}`;
        const feedbackNow = Date.now();
        const publishFeedback = evaluation.status !== "blocked"
          || feedbackKey !== lastBlockedFeedbackKey
          || feedbackNow - lastBlockedFeedbackAt >= 5 * 60_000;
        if (publishFeedback) {
          await addRecord(evaluation.feedback, evaluation.status === "blocked" ? "warning" : "info");
          if (evaluation.status === "blocked") {
            lastBlockedFeedbackKey = feedbackKey;
            lastBlockedFeedbackAt = feedbackNow;
          }
          if (!agentCanRun()) return;
          try {
            await postEvent(`【千川 Agent 任务反馈】\n${evaluation.feedback}`,
              `workflow-${state.accountKey}-${state.scope}-${evaluation.runtime.lastRunAt}`);
          } catch (error) {
            if (handleFatalRuntimeError(error)) return;
          }
        }
        if (!agentCanRun()) return;
        for (const notification of evaluation.notifications || []) {
          if (!agentCanRun()) return;
          await deliverNotification(notification);
        }
        if (!evaluation.action) {
          updateAgentPhase(evaluation.status === "blocked" ? "attention" : "monitoring", evaluation.feedback);
          return;
        }
        const cooldown = await inspectPlanControlCooldown(evaluation.action, snapshot);
        if (cooldown?.allowed !== true) {
          const message = String(cooldown?.message || "每计划 1 小时调控限制校验失败，本轮未执行。").slice(0, 240);
          state.workflowRuntime = workflowApi.markActionSettled(state.workflowRuntime, true);
          await addRecord(message, "warning");
          updateAgentPhase("monitoring", message);
          return;
        }
        const existing = state.proposals.find((item) => item.workflowAction && !item.done
          && item.payload?.action === evaluation.action.action
          && item.payload?.target_id === evaluation.action.target_id);
        if (existing) {
          updateAgentPhase("attention", "已有调控建议等待人工处理");
          return;
        }
        const notificationReady = state.miniapp?.connected
          || state.weixin.ready
          || state.feishu.notificationsReady;
        if (config.executionMode === "managed" && (!state.status.ready || !notificationReady)) {
          await addRecord("全托管等待 · 客户端或通知通道离线，本轮未执行调控。", "warning");
          updateAgentPhase("attention", "全托管等待客户端或通知通道恢复");
          return;
        }
        if (!agentCanRun()) return;
        const proposal = normalizeProposal({ kind: "action", payload: evaluation.action });
        proposal.workflowAction = true;
        proposal.automatic = config.executionMode === "managed";
        state.proposals.push(proposal);
        if (config.executionMode === "managed") {
          setBusy(false);
          if (!agentCanRun()) return;
          await executeProposal(proposal, "managed");
          if (!agentCanRun()) return;
          state.workflowRuntime = workflowApi.markActionSettled(state.workflowRuntime, proposal.executionStatus === "succeeded");
          await saveStore();
        } else {
          await addRecord(`等待人工确认 · ${evaluation.feedback.split(" · ").slice(-1)[0]}`, "pending");
          updateAgentPhase("attention", "有调控建议等待人工确认");
        }
      } catch (error) {
        if (handleFatalRuntimeError(error)) return;
        await addRecord(`巡检停止 · ${String(error?.message || "规则任务运行失败").slice(0, 240)}`, "error").catch(() => null);
        state.status = { ready: state.status.ready, message: error.message || "规则任务运行失败" };
        updateAgentPhase(agentCanRun() ? "attention" : "off", error?.message || "规则任务需要处理");
      } finally {
        setBusy(false);
        render();
      }
    }

    async function confirm(proposalId) {
      if (!agentCanRun()) return;
      const proposal = state.proposals.find((item) => item.id === proposalId && item.workflowAction && !item.done);
      if (!proposal) return;
      await executeProposal(proposal, "command_confirmed");
      if (!agentCanRun()) return;
      state.workflowRuntime = workflowApi.markActionSettled(state.workflowRuntime, proposal.executionStatus === "succeeded");
      await saveStore().catch(() => null);
    }

    async function dismiss(proposalId) {
      const proposal = state.proposals.find((item) => item.id === proposalId && item.workflowAction && !item.done);
      if (!proposal) return;
      proposal.done = true;
      proposal.result = "用户已取消，本次未执行。";
      state.workflowRuntime = workflowApi.markActionSettled(state.workflowRuntime, true);
      await addRecord(`用户取消 · ${actionLabels[proposal.payload.action] || proposal.payload.action} · 计划 ${proposal.payload.target_id}`, "info");
      render();
    }

    return Object.freeze({ loadStore, saveStore, readDraft, compactText, mergeRecords, addRecord, run, runDataReport, confirm, dismiss });
  }

  const api = Object.freeze({ createWorkflowRuntime });
  if (typeof window !== "undefined") window.MMWQianchuanWorkflowRuntime = api;
  if (typeof module !== "undefined" && module.exports) module.exports = api;
})();
