(() => {
  const CONTRACT_VERSION = "1.0.0";
  const SCHEMA_VERSION = 1;
  const STATUSES = [
    "blocked", "cancelled", "completed", "executing", "observing", "planning", "received",
    "resolving_target", "retryable_failure", "safety_terminated", "verifying", "waiting_user"
  ];
  const TERMINAL_STATUSES = ["blocked", "cancelled", "completed", "safety_terminated"];
  const ERROR_CODES = [
    "CANCELLED", "CAPTCHA_BLOCKED", "CONTROL_NOT_FOUND", "DELIVERY_FAILED", "LEASE_CONFLICT",
    "LEASE_EXPIRED", "LOGIN_EXPIRED", "MODEL_ROUTE_FAILED", "PAGE_CHANGED",
    "PLATFORM_CONFIRM_REQUIRED", "RETRY_EXHAUSTED", "RISK_VERIFICATION", "SAFETY_BLOCKED",
    "TARGET_NOT_UNIQUE", "TIMEOUT", "VERIFICATION_MISMATCH", "WORKER_OFFLINE"
  ];
  const REDACTIONS = ["selector", "coordinates", "script", "html", "screenshot", "token", "cookie", "apiKey"];
  const RECOVERY = {
    CANCELLED: ["cancelled", false], CAPTCHA_BLOCKED: ["safety_terminated", false],
    CONTROL_NOT_FOUND: ["retryable_failure", true], DELIVERY_FAILED: ["retryable_failure", true],
    LEASE_CONFLICT: ["retryable_failure", true], LEASE_EXPIRED: ["retryable_failure", true],
    LOGIN_EXPIRED: ["waiting_user", false], MODEL_ROUTE_FAILED: ["retryable_failure", true],
    PAGE_CHANGED: ["observing", true], PLATFORM_CONFIRM_REQUIRED: ["observing", true],
    RETRY_EXHAUSTED: ["blocked", false], RISK_VERIFICATION: ["safety_terminated", false],
    SAFETY_BLOCKED: ["safety_terminated", false], TARGET_NOT_UNIQUE: ["waiting_user", false],
    TIMEOUT: ["retryable_failure", true], VERIFICATION_MISMATCH: ["retryable_failure", true],
    WORKER_OFFLINE: ["retryable_failure", true]
  };

  function tool(permission, available, required = [], adapter = "", verifier = "", retryableErrors = []) {
    return Object.freeze({
      permission, available, required: Object.freeze(required), adapter, verifier,
      retryableErrors: Object.freeze(retryableErrors), auditRedactions: Object.freeze([...REDACTIONS]),
      requiresWriteLease: permission === "write"
    });
  }

  const TOOLS = Object.freeze({
    read_account_overview: tool("read", true, [], "readonly_observer", "account_snapshot"),
    read_account_balance: tool("read", false),
    list_plans: tool("read", true, [], "page_context", "plan_list_snapshot"),
    read_plan_state: tool("read", true, ["planId"], "action_executor_observe", "plan_identity_snapshot"),
    open_plan: tool("navigation", true, ["planId"], "remote_control_open_target", "plan_page_identity", ["PAGE_CHANGED", "CONTROL_NOT_FOUND"]),
    set_plan_roi: tool("write", true, ["planId", "expectedBefore", "targetValue"], "operation_state_machine_set_roi", "plan_value_refresh", ["PAGE_CHANGED", "CONTROL_NOT_FOUND", "PLATFORM_CONFIRM_REQUIRED", "VERIFICATION_MISMATCH"]),
    set_plan_budget: tool("write", true, ["planId", "expectedBefore", "targetValue"], "operation_state_machine_set_budget", "plan_value_refresh", ["PAGE_CHANGED", "CONTROL_NOT_FOUND", "PLATFORM_CONFIRM_REQUIRED", "VERIFICATION_MISMATCH"]),
    pause_plan: tool("write", true, ["planId", "expectedBefore"], "operation_state_machine_pause", "plan_status_refresh", ["PAGE_CHANGED", "CONTROL_NOT_FOUND", "PLATFORM_CONFIRM_REQUIRED", "VERIFICATION_MISMATCH"]),
    resume_plan: tool("write", true, ["planId", "expectedBefore"], "operation_state_machine_resume", "plan_status_refresh", ["PAGE_CHANGED", "CONTROL_NOT_FOUND", "PLATFORM_CONFIRM_REQUIRED", "VERIFICATION_MISMATCH"]),
    switch_qianchuan_scope: tool("navigation", true, ["targetScope"], "remote_control_navigation", "account_scope_page", ["PAGE_CHANGED", "CONTROL_NOT_FOUND"]),
    read_current_page: tool("read", true, [], "readonly_observer", "account_scope_page"),
    send_weixin_report: tool("delivery", true, ["message"], "weixin_delivery_job", "delivery_receipt", ["DELIVERY_FAILED"])
  });

  function getTool(name) {
    const contract = TOOLS[String(name || "")];
    if (!contract) throw new Error("千川业务工具不在白名单中。");
    return contract;
  }

  function assertAvailable(name, args = {}) {
    const contract = getTool(name);
    if (!contract.available) throw Object.assign(new Error("当前版本没有该业务工具的真实页面适配器。"), { code: "CONTROL_NOT_FOUND" });
    for (const field of contract.required) {
      if (args[field] === undefined || args[field] === null || args[field] === "") {
        throw new Error(`千川业务工具缺少参数：${field}`);
      }
    }
    return contract;
  }

  function publicContract() {
    return {
      contractVersion: CONTRACT_VERSION,
      schemaVersion: SCHEMA_VERSION,
      statuses: [...STATUSES],
      terminalStatuses: [...TERMINAL_STATUSES],
      errorCodes: [...ERROR_CODES],
      tools: Object.fromEntries(Object.entries(TOOLS).map(([name, entry]) => [name, {
        permission: entry.permission, available: entry.available, required: [...entry.required],
        adapter: entry.adapter, verifier: entry.verifier, retryableErrors: [...entry.retryableErrors],
        auditRedactions: [...entry.auditRedactions], requiresWriteLease: entry.requiresWriteLease
      }])),
      recovery: Object.fromEntries(Object.entries(RECOVERY).map(([code, [status, retryable]]) => [code, { status, retryable }]))
    };
  }

  const api = Object.freeze({ CONTRACT_VERSION, SCHEMA_VERSION, STATUSES, TERMINAL_STATUSES, ERROR_CODES, TOOLS, getTool, assertAvailable, publicContract });
  if (typeof window !== "undefined") window.MMWQianchuanTaskContract = api;
  if (typeof module !== "undefined" && module.exports) module.exports = api;
})();
