(function () {
  // Patch out supportsImageBitmap as that doesn't load some images when XHR is patched out
  // We override the setting in configure before we load assets
  var oldAppConfigure = pc.Application.prototype.configure;
  pc.Application.prototype.configure = function (json, callback) {
    this.graphicsDevice.supportsImageBitmap = false;
    oldAppConfigure.call(this, json, callback);
  };

  var oldGet = pc.Http.prototype.get;
  pc.Http.prototype.get = function get(url, options, callback) {
    if (typeof options === "function") {
      callback = options;
      options = {};
    }

    // 如果 url 是对象，直接返回（用于内联 config JSON）
    if (typeof url === 'object') {
      callback(null, url);
      return;
    }

    if (typeof url !== 'string' || !url.includes(',')) {
      // 回退到原始行为
      return oldGet.call(this, url, options, callback);
    }

    var index = url.indexOf(',');
    var base64 = url.slice(index + 1);
    
    // 移除查询参数（如 ?t=hash 用于缓存破坏）
    var queryIndex = base64.indexOf('?');
    if (queryIndex !== -1) {
      base64 = base64.substring(0, queryIndex);
    }
    
    // 防御性检查：清理 base64 字符串，移除空白字符
    base64 = base64.trim().replace(/\s/g, '');
    
    // 如果 base64 为空，返回空数据
    if (!base64) {
      console.warn('警告: base64 数据为空，URL:', url.substring(0, 100));
      callback(null, url.startsWith('data:image/') ? new Blob([]) : '');
      return;
    }
    
    var data;
    try {
      data = window.atob(base64);
    } catch (e) {
      console.error('atob 解码失败:', e.message, 'URL:', url.substring(0, 100));
      callback('atob 解码失败: ' + e.message);
      return;
    }

    if (url.startsWith('data:application/json') || options.responseType === pc.Http.ResponseType.JSON) {
      data = JSON.parse(data);
    } else if (url.startsWith('data:text/plain')) {
      // Do nothing
    } else {
      // Assume binary if not JSON
      var len = data.length;
      var bytes = new Uint8Array(len);
      for (var i = 0; i < len; i++) {
        bytes[i] = data.charCodeAt(i);
      }
      data = bytes.buffer;

      if (url.startsWith('data:image/')) {
        data = new Blob([data]); 
      }
    }

    callback(null, data);
  };
})();
