/**
 * 修复新加坡Nginx配置 + 修复广州配置冲突
 */

const SG = { ip: '43.156.237.110', port: 3911, key: 'zy_gtw_74d30f54fa8b5581514569ee7874def57861a31ccb2be8c9' }
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 readFile(srv, path) {
  const r = await callGK(srv, 'POST', '/file/read', { path })
  if (r.status === 200) return r.data.content
  return null
}

async function writeFile(srv, path, content) {
  return (await callGK(srv, 'POST', '/file/write', { path, content })).status === 200
}

async function main() {
  console.log('═'.repeat(50))
  console.log('🔧 修复Nginx配置')
  console.log('═'.repeat(50))

  // === 新加坡修复 ===
  console.log('\n📌 新加坡: 将/images/注入默认server块')

  // 读取默认配置
  const defaultConf = await readFile(SG, '/etc/nginx/sites-enabled/default')
  if (!defaultConf) {
    console.log('  ❌ 无法读取默认配置')
    return
  }

  // 删除之前创建的冲突配置
  await exec(SG, 'rm -f /etc/nginx/sites-enabled/image-studio /etc/nginx/sites-available/image-studio 2>&1')
  console.log('  ✅ 删除冲突的server块')

  // 在server块中注入/images/ location
  // 找到第一个server块在http块（default文件里）或直接根级别
  // 在server块的最后一个}之前插入location /images/
  
  // 找server块最后的}
  const lastBraceBeforeEnd = defaultConf.lastIndexOf('}')
  if (lastBraceBeforeEnd === -1) {
    console.log('  ❌ 找不到server块结尾')
    return
  }

  const imagesLoc = `
    # 铸渊图片工作室 · 代理到本地3912
    location /images/ {
        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;
    }
}
`
  const newDefault = defaultConf.slice(0, lastBraceBeforeEnd) + imagesLoc

  if (await writeFile(SG, '/etc/nginx/sites-enabled/default', newDefault)) {
    console.log('  ✅ 默认配置更新成功')
  }

  // 测试+重载
  const r1 = await exec(SG, 'nginx -t 2>&1')
  console.log('  Nginx测试:', r1.stdout || r1.stderr)
  const r2 = await exec(SG, 'nginx -s reload 2>&1')
  console.log('  Nginx重载:', r2.stdout || r2.stderr || 'ok')

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

  // === 广州修复 ===
  console.log('\n📌 广州: 删除guanghulab.bak避免conflict')
  await exec(GZ, 'rm -f /etc/nginx/sites-enabled/guanghulab.bak 2>&1')
  console.log('  ✅ 删除.bak备份')

  // 检查是否有sites-available的guanghulab.conf被软链到了sites-enabled
  const r4 = await exec(GZ, 'ls -la /etc/nginx/sites-enabled/')
  console.log('  当前sites-enabled:', r4.stdout || r4.stderr)

  // 验证广州Nginx配置
  const r5 = await exec(GZ, 'nginx -t 2>&1')
  console.log('  广州Nginx测试:', r5.stdout || r5.stderr)
  const r6 = await exec(GZ, 'nginx -s reload 2>&1')
  console.log('  广州Nginx重载:', r6.stdout || r6.stderr || 'ok')

  // === 广州到新加坡全部链路测试 ===
  console.log('\n' + '═'.repeat(50))
  console.log('📡 全链路测试')
  console.log('═'.repeat(50))

  // 1. 新加坡本地 → image-studio
  const r7 = await exec(SG, 'curl -s http://localhost:3912/ | head -2')
  console.log('  1. SG local:3912:', r7.stdout || r7.stderr)

  // 2. 新加坡 Nginx → image-studio
  const r8 = await exec(SG, 'curl -s http://localhost/images/ | head -2')
  console.log('  2. SG nginx /images:', r8.stdout || r8.stderr)

  // 3. 广州 → 新加坡80端口/images
  const r9 = await exec(GZ, `curl -s --connect-timeout 5 http://${SG.ip}/images/ | head -2`)
  console.log('  3. GZ→SG /images:', r9.stdout || r9.stderr || '(空)')

  // 4. 广州 Nginx → 新加坡 (https://guanghulab.com/images/)
  const r10 = await exec(GZ, 'curl -s -k --connect-timeout 5 https://localhost/images/ | head -2')
  console.log('  4. GZ nginx /images:', r10.stdout || r10.stderr || '(空)')

  // 测试直接访问新加坡80端口
  console.log('\n  测试新加坡80端口根路径:')
  const r11 = await exec(GZ, `curl -s --connect-timeout 5 http://${SG.ip}/ | head -3`)
  console.log('  ', r11.stdout || r11.stderr || '(空)')

  console.log('\n' + '═'.repeat(50))
  console.log('✅ 修复完成')
  console.log('═'.repeat(50))
}

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