/**
 * 测试广州→新加坡网络连通性，然后配置Nginx
 */
const SERVERS = {
  sg: { name: '新加坡·铸渊大脑', ip: '43.156.237.110', port: 3911, key: 'zy_gtw_74d30f54fa8b5581514569ee7874def57861a31ccb2be8c9' },
  gz: { name: '广州·代码仓库',   ip: '43.139.217.141', port: 3910, key: 'zy_gtw_4a155446b7acc09fe46a2a29972c0ca5d9954da19c35dc23' },
}

async function callGatekeeper(server, method, path, body = null) {
  const url = `http://${server.ip}:${server.port}${path}`
  const opts = {
    method,
    headers: { 'Authorization': `Bearer ${server.key}`, 'Content-Type': 'application/json' },
  }
  if (body) opts.body = JSON.stringify(body)
  const res = await fetch(url, opts)
  const text = await res.text()
  let data
  try { data = JSON.parse(text) } catch { data = { raw: text } }
  return { status: res.status, data }
}

async function exec(server, cmd) {
  const result = await callGatekeeper(server, 'POST', '/exec', { cmd })
  return result.data
}

async function readFile(server, path) {
  const result = await callGatekeeper(server, 'POST', '/file/read', { path })
  if (result.status === 200) return result.data.content
  return null
}

async function writeFile(server, path, content) {
  const result = await callGatekeeper(server, 'POST', '/file/write', { path, content })
  return result.status === 200
}

async function main() {
  const gz = SERVERS.gz
  const sg = SERVERS.sg

  // 测试广州→新加坡网络（详细）
  console.log('🔌 广州→新加坡 网络测试:')
  const r1 = await exec(gz, `curl -v --connect-timeout 5 http://${sg.ip}:3912/ 2>&1 | head -20`)
  console.log(r1.stdout || r1.stderr || 'empty')

  // 测试广州→新加坡 Gatekeeper (3911)
  console.log('\n🔌 广州→新加坡 Gatekeeper 测试:')
  const r2 = await exec(gz, `curl -s --connect-timeout 5 -X POST http://${sg.ip}:3911/ping 2>&1 | head -5`)
  console.log(r2.stdout || r2.stderr || 'empty')

  // 如果广州不能直接连新加坡，试试从新加坡创建反向隧道
  console.log('\n🔍 检查是否需要反向代理方案')
  
  // 查看新加坡的ufw防火墙
  const r3 = await exec(sg, 'ufw status 2>&1 || echo "ufw not active"')
  console.log('新加坡防火墙:', r3.stdout || r3.stderr)

  // 查看广州的防火墙
  const r4 = await exec(gz, 'ufw status 2>&1 || echo "ufw not active"')
  console.log('广州防火墙:', r4.stdout || r4.stderr)

  // 检查新加坡3912端口是否监听在0.0.0.0
  const r5 = await exec(sg, 'ss -tlnp | grep 3912')
  console.log('新加坡3912监听:', r5.stdout || r5.stderr)

  // 直接测试新加坡本地的3912
  const r6 = await exec(sg, 'curl -s http://localhost:3912/ | head -3')
  console.log('新加坡本地测试:', r6.stdout || r6.stderr)
}

main().catch(err => console.error('❌', err))
