/**
 * ═══════════════════════════════════════════════════
 * 铸渊远程部署 · 第三阶段：配置广州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 })
  if (result.status !== 200) {
    return { ok: false, error: result.data }
  }
  return { ok: true, stdout: result.data.stdout || '', stderr: result.data.stderr || '' }
}

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('═'.repeat(50))
  console.log('🌐 配置广州Nginx反向代理')
  console.log('═'.repeat(50))

  // 1. 查找所有Nginx配置相关文件
  console.log('\n📂 查找Nginx配置...')
  const lsResult = await exec(gz, 'find /etc/nginx -type f -name "*.conf" | sort')
  if (lsResult.ok) console.log(lsResult.stdout)

  // 2. 读取各个配置文件
  for (const p of ['/etc/nginx/conf.d/default.conf', '/etc/nginx/sites-enabled/default', '/etc/nginx/nginx.conf']) {
    const content = await readFile(gz, p)
    if (content) {
      console.log(`\n📄 ${p}:`)
      console.log(content.slice(0, 2000))
      if (content.length > 2000) console.log(`... (共${content.length}字符，截断显示)`)
    }
  }

  // 3. 查找已部署的站点信息
  console.log('\n🔍 查找站点的server_name...')
  await exec(gz, 'grep -r "server_name" /etc/nginx/ 2>/dev/null')
  
  // 4. 查看Forgejo的端口
  console.log('\n🔍 查找Forgejo端口...')
  await exec(gz, 'ss -tlnp | grep -E "3000|8080|3910"')
  
  // 5. 查找现有反向代理规则
  console.log('\n🔍 查找现有proxy_pass...')
  await exec(gz, 'grep -r "proxy_pass" /etc/nginx/ 2>/dev/null')

  // 6. 测试新加坡服务器是否能从广州访问
  console.log('\n🔗 测试广州→新加坡网络...')
  const gwTest = await exec(gz, `curl -s --connect-timeout 5 http://${sg.ip}:3912/ | head -3 || echo "无法连接"`)
  console.log(gwTest.stdout || gwTest.stderr)

  console.log('\n' + '═'.repeat(50))
  console.log('✅ Nginx调查完成, 准备配置代理')
  console.log('═'.repeat(50))
}

main().catch(err => {
  console.error('❌ 失败:', err.message)
  process.exit(1)
})
