/**
 * 解决网络连通性问题
 * 方案：在新加坡服务器安装Nginx或配置代理
 * 使得广州可以通过某个可达端口访问到image-studio
 */

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 testGzToSg(gz, port) {
  const r = await exec(gz, `curl -s --connect-timeout 3 -o /dev/null -w "%{http_code}" http://${SERVERS.sg.ip}:${port}/ 2>&1`)
  return r.stdout || r.stderr
}

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

  console.log('═'.repeat(50))
  console.log('🔧 方案A: 在新加坡服务器上安装Nginx做反向代理')
  console.log('═'.repeat(50))

  // 1. 检查新加坡是否有Nginx
  console.log('\n📋 检查新加坡服务器环境...')
  const r1 = await exec(sg, 'which nginx && nginx -v 2>&1 || echo "no nginx"')
  console.log('nginx:', r1.stdout || r1.stderr)

  // 2. 检查是否已安装socat
  const r2 = await exec(sg, 'which socat && socat -V 2>&1 | head -1 || echo "no socat"')
  console.log('socat:', r2.stdout || r2.stderr)

  // 3. 测试广州→新加坡的端口连通性（检查哪些端口是开的）
  console.log('\n📡 测试广州→新加坡各端口连通性...')
  for (const port of [80, 443, 3000, 8080, 8084, 3910, 3911, 3912]) {
    const r = await exec(gz, `timeout 3 bash -c "echo > /dev/tcp/${SERVERS.sg.ip}/${port}" 2>&1 && echo "✅ OPEN" || echo "❌ CLOSED"`)
    const status = (r.stdout || '').trim()
    if (status.includes('OPEN')) console.log(`  端口 ${port}: ✅ OPEN`)
  }

  // 4. 如果没有Nginx，安装Nginx
  const hasNginx = r1.stdout && !r1.stdout.includes('no nginx')
  if (!hasNginx) {
    console.log('\n📥 安装Nginx...')
    const r3 = await exec(sg, 'apt-get install -y -qq nginx 2>&1 | tail -3')
    console.log(r3.stdout || r3.stderr)
  }

  // 5. 配置Nginx反向代理到本地3912
  const nginxConf = `
server {
    listen 3913;
    server_name _;

    location / {
        proxy_pass http://127.0.0.1:3912;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_buffering off;
    }

    location /output/ {
        alias /data/image-studio/output/;
        add_header Access-Control-Allow-Origin *;
        add_header Cache-Control "public, max-age=3600";
    }
}
`
  console.log('\n📝 写入Nginx配置...')
  const r4 = await exec(sg, `cat > /etc/nginx/sites-available/image-studio << 'NGINX_CONF'
${nginxConf}
NGINX_CONF
cat /etc/nginx/sites-available/image-studio | head -5`)
  console.log(r4.stdout || r4.stderr)

  // 6. 启用站点
  await exec(sg, 'ln -sf /etc/nginx/sites-available/image-studio /etc/nginx/sites-enabled/ 2>&1')
  await exec(sg, 'nginx -t 2>&1')
  await exec(sg, 'systemctl reload nginx 2>&1 || nginx -s reload 2>&1')

  // 7. 验证
  console.log('\n✅ 验证Nginx代理...')
  const r5 = await exec(sg, 'ss -tlnp | grep 3913')
  console.log('3913监听:', r5.stdout || r5.stderr)
  const r6 = await exec(sg, 'curl -s http://localhost:3913/ | head -3')
  console.log('Nginx代理测试:', r6.stdout || r6.stderr)

  // 8. 重新测试广州→新加坡的端口
  console.log('\n📡 重新测试...')
  const r7 = await exec(gz, `timeout 3 bash -c "echo > /dev/tcp/${SERVERS.sg.ip}/3913" 2>&1 && echo "✅ OPEN" || echo "❌ CLOSED"`)
  console.log(`端口 3913: ${(r7.stdout || '').trim()}`)

  // 9. 用curl测试
  const r8 = await exec(gz, `curl -s --connect-timeout 5 http://${SERVERS.sg.ip}:3913/ | head -3`)
  console.log('广州→新加坡3913测试:', (r8.stdout || r8.stderr || 'empty').slice(0, 200))

  console.log('\n' + '═'.repeat(50))
  console.log('📋 网络配置完成')
  console.log('═'.repeat(50))
}

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