/**
 * 使用新加坡现有Nginx添加image-studio反向代理
 * 广州可以通过新加坡的80端口访问到image-studio
 */

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 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) {
  const r = await callGK(srv, 'POST', '/file/write', { path, content })
  return r.status === 200
}

async function main() {
  console.log('═'.repeat(50))
  console.log('🔧 配置新加坡Nginx + 广州Nginx')
  console.log('═'.repeat(50))

  // 1. 读取新加坡Nginx配置
  console.log('\n📄 新加坡Nginx已有配置:')
  
  const sites = [
    '/etc/nginx/sites-enabled/default',
    '/etc/nginx/sites-available/guanghubingshuo.com',
    '/etc/nginx/sites-available/guanghuclip.cn',
  ]
  
  for (const p of sites) {
    try {
      const content = await readFile(SG, p)
      if (content) {
        console.log(`\n--- ${p} ---`)
        console.log(content.slice(0, 1500))
        if (content.length > 1500) console.log('...(截断)')
      }
    } catch (e) {
      console.log(`  ${p}: 读取失败`)
    }
  }

  // 2. 查看新加坡Nginx的server_name
  console.log('\n🔍 新加坡server_name:')
  const r1 = await exec(SG, 'grep -rn "server_name" /etc/nginx/sites-enabled/ 2>&1')
  console.log(r1.stdout || r1.stderr)
  
  // 3. 查看已有的默认站点
  console.log('\n🔍 新加坡默认站点:')
  const r2 = await exec(SG, 'curl -s -H "Host: guanghubingshuo.com" http://localhost:80/ | head -5')
  console.log(r2.stdout || '(空)')
  
  const r3 = await exec(SG, 'curl -s http://localhost:80/ | head -5')
  console.log('  直接访问80端口:', r3.stdout || '(空)')

  // 4. 现在添加image-studio到新加坡Nginx
  console.log('\n' + '═'.repeat(50))
  console.log('📝 添加image-studio到新加坡Nginx')
  console.log('═'.repeat(50))
  
  // 在sites-available创建image-studio配置
  const sgImagesConf = `
# 铸渊图片工作室 · 通过新加坡Nginx代理到本地3912
server {
    listen 80;
    server_name _;

    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;
    }

    location /images/output/ {
        alias /data/image-studio/output/;
        add_header Access-Control-Allow-Origin *;
        add_header Cache-Control "public, max-age=3600";
    }
}
`
  await writeFile(SG, '/etc/nginx/sites-available/image-studio', sgImagesConf)
  console.log('  ✅ 配置文件写入')

  // 如果default已经存在且有server_name _，就把/images加到default里
  // 或者把image-studio软链到sites-enabled
  await exec(SG, 'ln -sf /etc/nginx/sites-available/image-studio /etc/nginx/sites-enabled/image-studio 2>&1')
  const r4 = await exec(SG, 'nginx -t 2>&1')
  console.log('  Nginx测试:', r4.stdout || r4.stderr)
  
  const r5 = await exec(SG, 'nginx -s reload 2>&1')
  console.log('  Nginx重载:', r5.stdout || r5.stderr || 'ok')

  // 5. 测试本地是否能通过/images访问
  const r6 = await exec(SG, 'curl -s http://localhost:80/images/ | head -3')
  console.log('\n  ✅ 本地验证 /images:', r6.stdout || r6.stderr)

  // 6. 从广州测试新加坡的/images
  const r7 = await exec(GZ, `curl -s --connect-timeout 5 http://${SG.ip}/images/ | head -3`)
  console.log('\n  📡 广州→新加坡 /images 测试:', r7.stdout || r7.stderr || '无响应')

  // 7. 配置广州Nginx
  console.log('\n' + '═'.repeat(50))
  console.log('📝 配置广州Nginx反向代理')
  console.log('═'.repeat(50))
  
  // 读取广州Nginx当前活跃配置
  const gzActive = await readFile(GZ, '/etc/nginx/sites-enabled/guanghulab')
  if (gzActive) {
    console.log('  当前配置长度:', gzActive.length, '字符')
    
    // 检查是否已有/images配置
    if (gzActive.includes('/images')) {
      console.log('  ⚠️ /images 已存在，跳过')
    } else {
      // 在server block的末尾（最后一个}之前）添加/images代理
      const insertPoint = gzActive.lastIndexOf('}')
      const imagesBlock = `
    # 铸渊图片工作室 · 新加坡服务器反向代理
    location /images/ {
        proxy_pass http://${SG.ip}/images/;
        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 newConfig = gzActive.slice(0, insertPoint) + imagesBlock
      if (await writeFile(GZ, '/etc/nginx/sites-enabled/guanghulab', newConfig)) {
        console.log('  ✅ 广州Nginx配置更新成功')
      } else {
        console.log('  ❌ 广州Nginx配置更新失败')
      }
    }
  }

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

  console.log('\n' + '═'.repeat(50))
  console.log('✅ 全部配置完成！')
  console.log('═'.repeat(50))
  console.log(`\n📎 访问地址:`)
  console.log(`  https://guanghulab.com/images/`)
  console.log(`  (广州Nginx → 新加坡Nginx → image-studio:3912)`)
}

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