/**
 * 修复Chrome路径 + 检查广州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() {
  // ====== 1. 修复Chrome路径 ======
  console.log('═'.repeat(50))
  console.log('🔧 修复1: Chrome浏览器路径')
  console.log('═'.repeat(50))
  
  // 找到puppeteer安装的chrome路径
  const r1 = await exec(SG, 'ls /root/.cache/puppeteer/chrome/linux-*/chrome-linux64/chrome 2>&1')
  const chromePath = (r1.stdout || '').trim()
  console.log('Chrome实际路径:', chromePath || '未找到')
  
  if (chromePath) {
    // 创建软链接到期望路径
    await exec(SG, `ln -sf ${chromePath} /usr/bin/google-chrome 2>&1`)
    await exec(SG, 'google-chrome --version 2>&1')
    console.log('✅ Chrome软链接已创建')

    // 安装缺少的依赖
    const r2 = await exec(SG, 'ldd /usr/bin/google-chrome 2>&1 | grep "not found" | head -10')
    if (r2.stdout) {
      console.log('缺少依赖:', r2.stdout)
      await exec(SG, 'apt-get install -y -qq libnss3 libnspr4 libatk1.0-0t64 libatk-bridge2.0-0t64 libcups2t64 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxrandr2 libgbm1 libpango-1.0-0 libcairo2 2>&1 | tail -3')
    }

    // 测试生成一张图
    console.log('\n📸 测试生成图片...')
    const r3 = await exec(SG, 'cd /data/image-studio && node generate.js --text "你好冰朔\n图片工作室已部署完成\n现在可以在新加坡服务器上生成图片了" --for "小红书" --output deploy_greeting 2>&1')
    console.log(r3.stdout || r3.stderr)
    
    // 验证图片文件
    const r4 = await exec(SG, 'ls -la /data/image-studio/output/deploy_greeting*.png 2>&1')
    console.log('图片文件:', r4.stdout || r4.stderr)
    
    // 测试通过Nginx访问图片
    const r5 = await exec(SG, 'ls /data/image-studio/output/deploy_greeting*.png 2>&1 | head -1 | xargs -I{} basename {}')
    const imgName = (r5.stdout || '').trim()
    if (imgName) {
      const r6 = await exec(SG, `curl -s -o /dev/null -w "HTTP:%{http_code} SIZE:%{size_download}" http://localhost/images/output/${imgName} 2>&1`)
      console.log(`通过Nginx访问图片:`, r6.stdout || r6.stderr)
    }
  }

  // ====== 2. 检查广州Nginx配置 ======
  console.log('\n' + '═'.repeat(50))
  console.log('🔧 修复2: 广州Nginx配置')
  console.log('═'.repeat(50))
  
  const gzConfig = await readFile(GZ, '/etc/nginx/sites-enabled/guanghulab')
  if (gzConfig) {
    console.log('广州Nginx配置(images部分):')
    const lines = gzConfig.split('\n')
    const imgLines = lines.filter(l => l.includes('images') || l.includes('43.156'))
    imgLines.forEach(l => console.log('  ' + l.trim()))
    
    // 检查是否有/images/配置
    if (!gzConfig.includes('/images/')) {
      console.log('❌ 广州Nginx缺少/images/代理配置')
    } else {
      console.log('✅ /images/代理配置存在')
      
      // 检查代理目标是否正确
      const proxyMatch = gzConfig.match(/proxy_pass\s+http:\/\/[^;]+\/images\//)
      if (proxyMatch) {
        console.log('代理目标:', proxyMatch[0])
      }
      
      // 测试广州Nginx本地访问
      console.log('\n测试广州Nginx:')
      const r7 = await exec(GZ, `curl -s -k --connect-timeout 5 -w "\\nHTTP:%{http_code}" https://localhost/images/ 2>&1 | tail -3`)
      console.log('  https://localhost/images/:', r7.stdout || r7.stderr)
      
      // 测试广州直接访问新加坡/images/（不含SSL）
      const r8 = await exec(GZ, `curl -s --connect-timeout 5 -w "\\nHTTP:%{http_code}" http://${SG.ip}/images/ 2>&1 | tail -3`)
      console.log('  http://SG_IP/images/:', r8.stdout || r8.stderr)
    }
  }

  // ====== 3. 尝试解决广州Nginx代理问题 ======
  console.log('\n' + '═'.repeat(50))
  console.log('🔧 修复3: 修正广州Nginx代理')
  console.log('═'.repeat(50))

  // 读取完整配置检查root位置
  const gzRoot = await readFile(GZ, '/etc/nginx/sites-enabled/guanghulab')
  if (gzRoot) {
    // 找到/images/的配置位置并检查
    const imgBlockStart = gzRoot.indexOf('location /images/')
    if (imgBlockStart >= 0) {
      const contextStart = Math.max(0, imgBlockStart - 100)
      const contextEnd = Math.min(gzRoot.length, imgBlockStart + 400)
      console.log('/images/配置上下文:')
      console.log(gzRoot.slice(contextStart, contextEnd))
    }
  }

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

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