/**
 * 在新加坡服务器上配置Nginx反向代理
 * 广州→新加坡的3911端口(Gatekeeper)是通的
 * 但3912端口不通。需要在新加坡本地装Nginx
 * 来代理访问，或者使用其他可通端口。
 */

const SG = {
  name: '新加坡·铸渊大脑', ip: '43.156.237.110', port: 3911,
  key: 'zy_gtw_74d30f54fa8b5581514569ee7874def57861a31ccb2be8c9'
}
const GZ = {
  name: '广州·代码仓库', ip: '43.139.217.141', port: 3910,
  key: 'zy_gtw_4a155446b7acc09fe46a2a29972c0ca5d9954da19c35dc23'
}

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

async function exec(srv, cmd) {
  const r = await callGK(srv, 'POST', '/exec', { cmd })
  return r.data
}

async function main() {
  // 第一步：检查新加坡服务器的开放端口
  console.log('📡 检查新加坡服务器已监听端口...')
  const r1 = await exec(SG, 'ss -tlnp')
  console.log(r1.stdout || r1.stderr)

  // 第二步：检查是否已有Nginx
  console.log('\n🔍 检查Nginx...')
  const r2 = await exec(SG, 'which nginx && nginx -v 2>&1 || echo "no nginx"')
  console.log(r2.stdout || r2.stderr)

  // 第三步：查看所有Nginx站点
  const r3 = await exec(SG, 'ls -la /etc/nginx/sites-enabled/ 2>&1 || echo "no sites-enabled"')
  console.log('\nNginx站点:', r3.stdout || r3.stderr)

  // 第四步：查看正在运行的服务，找到已经开放的端口
  console.log('\n🔍 检查其他服务端口...')
  const r4 = await exec(SG, 'curl -s --connect-timeout 3 http://localhost:80/ 2>&1 | head -3 || echo "port 80 not serving"')
  console.log('port 80:', r4.stdout || r4.stderr)
  const r5 = await exec(SG, 'curl -s --connect-timeout 3 http://localhost:3000/ 2>&1 | head -3 || echo "port 3000 not serving"')
  console.log('port 3000:', r5.stdout || r5.stderr)
  const r6 = await exec(SG, 'curl -s --connect-timeout 3 http://localhost:8080/ 2>&1 | head -3 || echo "port 8080 not serving"')
  console.log('port 8080:', r6.stdout || r6.stderr)

  // 第五步：从广州测试哪些端口到新加坡是通的
  console.log('\n📡 广州→新加坡端口测试...')
  const testPorts = [80, 443, 8080, 3000, 3910, 3911]
  for (const port of testPorts) {
    const r = await exec(GZ, `timeout 3 bash -c "echo > /dev/tcp/${SG.ip}/${port}" 2>&1 && echo '✅' || echo '❌'`)
    const status = (r.stdout || '').trim()
    console.log(`  端口 ${port}: ${status}`)
  }

  // 第六步：方案1 - 如果80端口可用，就用Nginx代理
  const r7 = await exec(SG, 'which nginx 2>&1 || apt-get install -y -qq nginx 2>&1 | tail -3')
  console.log('\n📥 Nginx安装:', (r7.stdout || r7.stderr).slice(0, 100))

  // 创建Nginx配置
  const nginxSiteConf = `server {
    listen 3914;
    server_name _;

    # 允许跨域
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
    add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range";

    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;
        proxy_read_timeout 60s;
    }

    location /output/ {
        alias /data/image-studio/output/;
        add_header Access-Control-Allow-Origin *;
        add_header Cache-Control "public, max-age=3600";
    }
}
`
  const r8 = await exec(SG, `cat > /etc/nginx/sites-available/image-studio << 'EOF'
${nginxSiteConf}
EOF`)
  console.log('\n📝 Nginx配置写入:', (r8.stdout || r8.stderr || 'ok').slice(0, 100))

  // 启用站点
  await exec(SG, 'ln -sf /etc/nginx/sites-available/image-studio /etc/nginx/sites-enabled/ 2>&1')
  const r9 = await exec(SG, 'nginx -t 2>&1')
  console.log('Nginx测试:', r9.stdout || r9.stderr)
  const r10 = await exec(SG, 'nginx -s reload 2>&1 || systemctl reload nginx 2>&1')
  console.log('Nginx重载:', r10.stdout || r10.stderr || 'ok')

  // 验证本地
  const r11 = await exec(SG, 'curl -s http://localhost:3914/ | head -3')
  console.log('\n✅ 本地验证:', r11.stdout || r11.stderr)

  // 从广州测试新端口
  const r12 = await exec(GZ, `timeout 3 bash -c "echo > /dev/tcp/${SG.ip}/3914" 2>&1 && echo '✅ OPEN' || echo '❌ CLOSED'`)
  console.log('广州→新加坡3914:', (r12.stdout || '').trim())

  // 如果3914也不行，做最终方案：直接用广州的Gatekeeper代理
  // 让广州的Nginx通过Gatekeeper API转发请求
  console.log('\n' + '═'.repeat(50))
  console.log('📋 配置完成')
  console.log('═'.repeat(50))
}

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