(() => {
  const WRITES = new Set(["set_plan_roi", "set_plan_budget", "pause_plan", "resume_plan"]);

  function verify(task = {}, observation = {}) {
    const base = identityEvidence(task, observation);
    const mismatch = identityMismatch(task, observation);
    if (mismatch) return outcome("retry", "VERIFICATION_MISMATCH", mismatch, base);
    if (observation.blockerCode) return blockedObservation(observation.blockerCode, base);
    if (!observation.pageFingerprint || !observation.observedAt) {
      return outcome("retry", "VERIFICATION_MISMATCH", "重新读取后的页面指纹或时间缺失。", base);
    }
    const toolName = String(task.toolName || "");
    if (WRITES.has(toolName) && !task.valueFrozen) {
      return outcome("blocked", "SAFETY_BLOCKED", "写任务没有冻结 expectedBefore 与绝对 targetValue。", base);
    }
    if (toolName === "set_plan_roi" || toolName === "set_plan_budget") {
      if (!sameNumber(observation.observedAfter, task.targetValue)) {
        return outcome("retry", "VERIFICATION_MISMATCH", "刷新后读取到的数值与绝对目标值不一致。", base);
      }
    } else if (toolName === "pause_plan") {
      if (normalizeStatus(observation.observedAfter) !== "paused") {
        return outcome("retry", "VERIFICATION_MISMATCH", "刷新后计划仍未暂停。", base);
      }
    } else if (toolName === "resume_plan") {
      if (normalizeStatus(observation.observedAfter) !== "active") {
        return outcome("retry", "VERIFICATION_MISMATCH", "刷新后计划仍未恢复投放。", base);
      }
    } else if (toolName === "open_plan") {
      if (observation.planPageOpen !== true) return outcome("retry", "PAGE_CHANGED", "页面没有停留在目标计划。", base);
    } else if (toolName === "switch_qianchuan_scope") {
      if (String(observation.scope || "") !== String(task.toolArgs?.targetScope || task.scope || "")) {
        return outcome("retry", "PAGE_CHANGED", "页面场景切换结果与目标场景不一致。", base);
      }
    } else if (["read_account_overview", "list_plans", "read_plan_state", "read_current_page"].includes(toolName)) {
      if (observation.dataAvailable !== true) return outcome("waiting_user", "CONTROL_NOT_FOUND", "当前页面没有可核验的数据。", base);
    } else if (toolName === "send_weixin_report") {
      if (!observation.receiptId || observation.deliveryStatus !== "delivered") {
        return outcome("retry", "DELIVERY_FAILED", "微信尚未返回真实送达回执。", base);
      }
      base.receiptId = String(observation.receiptId).slice(0, 160);
    } else {
      return outcome("blocked", "SAFETY_BLOCKED", "当前工具没有独立验证器。", base);
    }
    return outcome("completed", "", "已根据重新读取的独立证据确认任务完成。", base);
  }

  function identityMismatch(task, observation) {
    if (String(observation.accountKey || "") !== String(task.accountKey || "")) return "验证读取到了其他千川账户。";
    if (String(observation.scope || "") !== String(task.scope || "") && task.toolName !== "switch_qianchuan_scope") return "验证读取到了其他投放场景。";
    if (task.planId && String(observation.planId || "") !== String(task.planId)) return "验证读取到了其他计划 ID。";
    if (task.valueFrozen && !sameValue(observation.expectedBefore, task.expectedBefore)) return "验证证据中的原值与冻结原值不一致。";
    if (task.valueFrozen && !sameValue(observation.targetValue, task.targetValue)) return "验证证据中的目标值与冻结目标值不一致。";
    return "";
  }

  function identityEvidence(task, observation) {
    return {
      accountKey: String(observation.accountKey || "").slice(0, 128),
      accountName: String(observation.accountName || "").slice(0, 160),
      scope: String(observation.scope || "").slice(0, 40),
      scopeLabel: String(observation.scopeLabel || "").slice(0, 80),
      planId: String(observation.planId || "").slice(0, 64),
      expectedBefore: observation.expectedBefore ?? null,
      targetValue: observation.targetValue ?? null,
      observedAfter: observation.observedAfter ?? null,
      pageFingerprint: String(observation.pageFingerprint || "").slice(0, 128),
      observedAt: Number(observation.observedAt || 0),
      pageUpdatedText: String(observation.pageUpdatedText || "").slice(0, 160),
      dataSource: String(observation.dataSource || "qianchuan_page_dom").slice(0, 80)
    };
  }

  function blockedObservation(code, evidence) {
    const value = String(code || "").toUpperCase();
    const terminal = new Set(["CAPTCHA_BLOCKED", "RISK_VERIFICATION", "SAFETY_BLOCKED"]);
    const waiting = new Set(["LOGIN_EXPIRED"]);
    if (terminal.has(value)) return outcome("safety_terminated", value, "平台安全检查要求立即停止。", evidence);
    if (waiting.has(value)) return outcome("waiting_user", value, "需要用户恢复登录后再继续。", evidence);
    return outcome("blocked", "SAFETY_BLOCKED", "页面出现不允许自动处理的阻塞。", evidence);
  }

  function outcome(status, errorCode, reason, evidence) {
    return Object.freeze({ ok: status === "completed", status, errorCode, reason, evidence: Object.freeze({ ...evidence }) });
  }

  function sameNumber(left, right) {
    const a = Number(left), b = Number(right);
    return Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= 1e-8;
  }

  function sameValue(left, right) {
    if (typeof left === "number" || typeof right === "number") return sameNumber(left, right);
    return String(left ?? "") === String(right ?? "");
  }

  function normalizeStatus(value) {
    const text = String(value || "").trim().toLowerCase();
    if (["paused", "pause", "已暂停", "暂停"].includes(text)) return "paused";
    if (["active", "running", "enabled", "投放中", "已开启", "开启"].includes(text)) return "active";
    return text;
  }

  const api = Object.freeze({ verify, identityEvidence });
  if (typeof window !== "undefined") window.MMWQianchuanResultVerifier = api;
  if (typeof module !== "undefined" && module.exports) module.exports = api;
})();
