/**
 * 正确测试广州Nginx代理
 */

const GZ = { 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('═'.repeat(50))
  console.log('📡 广州Nginx全链路测试')
  console.log('═'.repeat(50))

  // 1. 测试本地Nginx + 正确Host头
  console.log('\n1️⃣  本地Nginx + Host头:')
  const tests = [
    ['https://localhost/images/ (默认Host)', `curl -s -k --connect-timeout 5 -w "\\nHTTP:%{http_code}" https://localhost/images/ 2>&1 | tail -3`],
    ['https://localhost/images/ (Host:guanghulab.com)', `curl -s -k --connect-timeout 5 -H "Host: guanghulab.com" -w "\\nHTTP:%{http_code}" https://localhost/images/ 2>&1 | tail -3`],
    ['http://localhost/images/ (Host:guanghulab.com)', `curl -s --connect-timeout 5 -H "Host: guanghulab.com" -w "\\nHTTP:%{http_code}" http://localhost/images/ 2>&1 | tail -3`],
    ['https://localhost/ (首页)', `curl -s -k --connect-timeout 5 -H "Host: guanghulab.com" -w "\\nHTTP:%{http_code}" https://localhost/ 2>&1 | tail -3`],
  ]

  for (const [name, cmd] of tests) {
    const r = await exec(GZ, cmd)
    console.log(`  ${name}:`)
    console.log(`    ${(r.stdout || r.stderr || '').split('\\n').slice(-3).join('\\n    ')}`)
  }

  // 2. 查看Nginx的错误日志
  console.log('\n2️⃣  Nginx错误日志(最后10行):')
  const r1 = await exec(GZ, 'tail -10 /var/log/nginx/error.log 2>&1 || echo "no error log"')
  console.log('  ', (r1.stdout || r1.stderr || '').slice(0, 500))

  // 3. 检查代理的配置是否真的在正确位置
  console.log('\n3️⃣  完整SSL server块检查:')
  const r2 = await exec(GZ, "sed -n '/listen 443 ssl/,/^}$/p' /etc/nginx/sites-enabled/guanghulab | head -60")
  console.log(r2.stdout || r2.stderr)

  // 4. 也检查一下Nginx的端口监听状态
  console.log('\n4️⃣  Nginx端口:')
  const r3 = await exec(GZ, 'ss -tlnp | grep nginx')
  console.log(r3.stdout || r3.stderr)

  // 5. 直接通过新加坡IP测试广州的代理设置
  console.log('\n5️⃣  通过广州访问新加坡/images/:')
  const SG_IP = '43.156.237.110'
  const r4 = await exec(GZ, `curl -s --connect-timeout 5 -w "\\nHTTP:%{http_code}" http://${SG_IP}/images/ -H "Host: guanghulab.com" 2>&1 | tail -3`)
  console.log('  http://SG_IP/images/ (Host:guanghulab.com):', (r4.stdout || '').slice(0, 100))
}

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