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

  const SCHEMA_VERSION = 1;
  const COOLDOWN_MS = 60 * 60 * 1000;
  const STORAGE_PREFIX = "mmw.qianchuanAgent.planControlCooldown.v1:";
  const PLAN_ID_PATTERN = /^\d{10,24}$/;
  const COOLDOWN_ACTION = "set_roi";

  function parseTime(value) {
    const numeric = Number(value);
    if (Number.isFinite(numeric) && numeric > 0) return numeric;
    const parsed = Date.parse(String(value || "").replace(" ", "T"));
    return Number.isFinite(parsed) ? parsed : 0;
  }

  function normalizeContext(value = {}) {
    return {
      accountKey: String(value.accountKey || "").trim(),
      scope: String(value.scope || "").trim(),
      supported: value.supported === true
    };
  }

  function storageKey(context) {
    return `${STORAGE_PREFIX}${encodeURIComponent(context.accountKey)}:${encodeURIComponent(context.scope)}`;
  }

  function createPlanControlCooldown(options = {}) {
    const chromeApi = options.chromeApi;
    const getContext = typeof options.getContext === "function" ? options.getContext : () => ({});
    const getAudits = typeof options.getAudits === "function" ? options.getAudits : () => [];
    const now = typeof options.now === "function" ? options.now : () => Date.now();

    function contextOrError() {
      const context = normalizeContext(getContext());
      if (!context.supported || !context.accountKey || !context.scope) {
        throw new Error("当前千川账号或投放场景不明确，无法校验每计划 1 小时调控限制，本次未执行。");
      }
      return context;
    }

    function planIdOrError(payload) {
      const planId = String(payload?.target_id || payload?.targetId || "").trim();
      if (!PLAN_ID_PATTERN.test(planId)) {
        throw new Error("计划 ID 不明确，无法校验每计划 1 小时调控限制，本次未执行。");
      }
      return planId;
    }

    function loadStore(context) {
      const key = storageKey(context);
      if (typeof chromeApi?.storage?.local?.get !== "function") {
        return Promise.reject(new Error("调控计时存储不可用，本次未执行。"));
      }
      return new Promise((resolve, reject) => {
        chromeApi.storage.local.get(key, (values) => {
          const error = chromeApi?.runtime?.lastError;
          if (error) reject(new Error(error.message || "调控计时读取失败，本次未执行。"));
          else {
            const value = values?.[key];
            resolve(value && typeof value === "object" ? value : { schemaVersion: SCHEMA_VERSION, plans: {} });
          }
        });
      });
    }

    function saveStore(context, value) {
      const key = storageKey(context);
      if (typeof chromeApi?.storage?.local?.set !== "function") {
        return Promise.reject(new Error("调控计时存储不可用，计时未保存。"));
      }
      return new Promise((resolve, reject) => {
        chromeApi.storage.local.set({ [key]: value }, () => {
          const error = chromeApi?.runtime?.lastError;
          if (error) reject(new Error(error.message || "调控计时保存失败。"));
          else resolve();
        });
      });
    }

    function latestAuditTime(context, planId) {
      return (Array.isArray(getAudits()) ? getAudits() : []).reduce((latest, audit) => {
        if (audit?.status !== "succeeded" || String(audit?.action || "") !== COOLDOWN_ACTION) return latest;
        if (String(audit?.target_id || "").trim() !== planId) return latest;
        if (audit?.account_key && String(audit.account_key) !== context.accountKey) return latest;
        if (audit?.scope && String(audit.scope) !== context.scope) return latest;
        return Math.max(latest, parseTime(audit.created_at || audit.createdAt || audit.confirmed_at || audit.confirmedAt));
      }, 0);
    }

    async function inspect(payload) {
      const action = String(payload?.action || "");
      if (action !== COOLDOWN_ACTION) return { allowed: true, code: "NOT_ROI_CONTROL", remainingMinutes: 0 };
      const context = contextOrError();
      const planId = planIdOrError(payload);
      const store = await loadStore(context);
      const localTime = parseTime(store?.plans?.[planId]?.lastControlAt);
      const lastControlAt = Math.max(localTime, latestAuditTime(context, planId));
      const elapsed = Math.max(0, now() - lastControlAt);
      if (!lastControlAt || elapsed >= COOLDOWN_MS) {
        return { allowed: true, code: lastControlAt ? "COOLDOWN_EXPIRED" : "FIRST_CONTROL", remainingMinutes: 0 };
      }
      const remainingMinutes = Math.max(1, Math.ceil((COOLDOWN_MS - elapsed) / 60000));
      return {
        allowed: false,
        code: "PLAN_CONTROL_COOLDOWN",
        remainingMinutes,
        lastControlAt,
        message: `计划 ${planId} 在 1 小时内已成功调整过 ROI；为保留千川当日成本保障，还需等待约 ${remainingMinutes} 分钟，本次 ROI 调整未执行。暂停、恢复和预算调整不占用也不受此计时限制。`
      };
    }

    async function recordSuccess(payload, status) {
      const action = String(payload?.action || "");
      if (status !== "succeeded" || action !== COOLDOWN_ACTION) return false;
      const context = contextOrError();
      const planId = planIdOrError(payload);
      const store = await loadStore(context);
      const recordedAt = now();
      const plans = Object.fromEntries(Object.entries(store?.plans && typeof store.plans === "object" ? store.plans : {})
        .filter(([, item]) => recordedAt - parseTime(item?.lastControlAt) < 30 * 24 * 60 * 60 * 1000)
        .sort(([, left], [, right]) => parseTime(right?.lastControlAt) - parseTime(left?.lastControlAt))
        .slice(0, 199));
      plans[planId] = { lastControlAt: recordedAt, action };
      await saveStore(context, { schemaVersion: SCHEMA_VERSION, plans, updatedAt: recordedAt });
      return true;
    }

    return Object.freeze({ inspect, recordSuccess });
  }

  const api = Object.freeze({ SCHEMA_VERSION, COOLDOWN_MS, STORAGE_PREFIX, createPlanControlCooldown });
  if (typeof window !== "undefined") window.MMWQianchuanPlanControlCooldown = api;
  if (typeof module !== "undefined" && module.exports) module.exports = api;
})();
