const hookScript = (): void => {
    const proxyBase = 'http://10.213.6.207:19010';

    const domainMap: Record<string, string> = {
        // --- 核心 API ---
        'https://webapi.amap.com/maps': '/maps',      // JS API 入口
        'https://webapi.amap.com': '/webAmap',   // 静态资源/插件
        'https://c-webapi.amap.com': '/cwebAmap',  // [新增] 辅助配置接口
        'https://restapi.amap.com': '/restAmap',  // 服务接口(搜索/地理编码等)
        'https://a.amap.com': '/amap',      // 辅助资源
        'https://lbs.amap.com': '/lbs',       // LBS 服务

        // --- 矢量瓦片 ---
        'https://vdata.amap.com': '/vdata',
        'https://vdata01.amap.com': '/vdata01',
        'https://vdata02.amap.com': '/vdata02',
        'https://vdata03.amap.com': '/vdata03',
        'https://vdata04.amap.com': '/vdata04',

        // --- 卫星图瓦片 ---
        'https://webst01.is.autonavi.com': '/webst01',
        'https://webst02.is.autonavi.com': '/webst02',
        'https://webst03.is.autonavi.com': '/webst03',
        'https://webst04.is.autonavi.com': '/webst04',

        // --- 栅格图瓦片 ---
        'https://wprd01.is.autonavi.com': '/wprd01',
        'https://wprd02.is.autonavi.com': '/wprd02',
        'https://wprd03.is.autonavi.com': '/wprd03',
        'https://wprd04.is.autonavi.com': '/wprd04',

        // --- 矢量数据 (HTTP 协议) ---
        'http://vector.amap.com': '/vector',
    };

    /**
     * URL 替换核心逻辑
     */
    const replaceUrl = (url: string): string => {
        // 如果已经是代理地址，不再处理
        if (url.indexOf(proxyBase) !== -1) {
            return url;
        }

        for (const [origin, path] of Object.entries(domainMap)) {
            if (url.indexOf(origin) !== -1) {
                // 将原始域名替换为: http://10.213.6.207:19010/xxx
                return url.replace(origin, `${proxyBase}${path}`);
            }
        }
        return url;
    };

    const scriptDescriptor = Object.getOwnPropertyDescriptor(HTMLScriptElement.prototype, 'src');
    if (scriptDescriptor && scriptDescriptor.set) {
        const nativeSet = scriptDescriptor.set;
        Object.defineProperty(HTMLScriptElement.prototype, 'src', {
            set: function (url: string) {
                const newUrl = replaceUrl(url);
                nativeSet.call(this, newUrl);
            },
            get: scriptDescriptor.get,
            configurable: true
        });
    }


    const nativeOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function (
        method: string,
        url: string | URL,
        async: boolean = true,
        user?: string | null,
        password?: string | null
    ): void {
        const strUrl = url.toString();
        const newUrl = replaceUrl(strUrl);
        return nativeOpen.call(this, method, newUrl, async, user, password);
    };

    console.log('[AMap Proxy] 高德地图内网代理拦截已激活 (包含 c-webapi 支持)');
};

hookScript();