// 让 Vercel CLI（经典 https/node-fetch，不读 HTTP(S)_PROXY 环境变量）走本地代理。
// 用法：PROXY_URL=http://127.0.0.1:10087 NODE_OPTIONS="-r ./proxy-bootstrap.cjs" vercel ...
const http = require('http')
const https = require('https')
const { HttpProxyAgent } = require('http-proxy-agent')
const { HttpsProxyAgent } = require('https-proxy-agent')

const proxyUrl = process.env.PROXY_URL || process.env.HTTPS_PROXY || process.env.https_proxy
if (!proxyUrl) {
  console.warn('[proxy-bootstrap] 未设置 PROXY_URL，跳过代理注入')
  module.exports = {}
} else {
  const httpAgent = new HttpProxyAgent(proxyUrl)
  const httpsAgent = new HttpsProxyAgent(proxyUrl)
  http.globalAgent = httpAgent
  https.globalAgent = httpsAgent

  const makePatch = (orig, agent) => function (arg1, arg2, arg3) {
    let url, options, cb
    if (typeof arg1 === 'string' || arg1 instanceof URL) {
      url = arg1
      if (typeof arg2 === 'function') { options = {}; cb = arg2 } else { options = arg2 || {}; cb = arg3 }
    } else {
      options = arg1 || {}; cb = arg2
    }
    if (!options.agent) options.agent = agent
    return url !== undefined ? orig.call(this, url, options, cb) : orig.call(this, options, cb)
  }

  const origHttpRequest = http.request
  const origHttpsRequest = https.request
  const origHttpGet = http.get
  const origHttpsGet = https.get
  http.request = makePatch(origHttpRequest, httpAgent)
  https.request = makePatch(origHttpsRequest, httpsAgent)
  http.get = makePatch(origHttpGet, httpAgent)
  https.get = makePatch(origHttpsGet, httpsAgent)

  console.warn('[proxy-bootstrap] 已注入代理：' + proxyUrl)
}
