/**
 * 检查location插入位置并修复
 */

const SG = { ip: '43.156.237.110', port: 3911, key: 'zy_gtw_74d30f54fa8b5581514569ee7874def57861a31ccb2be8c9' }

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() {
  // 查看50-75行
  const c1 = await exec(SG, 'cat -n /etc/nginx/sites-enabled/default | sed -n \'40,80p\'')
  console.log('=== 40-80行 ===')
  console.log(c1.stdout || c1.stderr)

  // 也在最后几行看看
  const c2 = await exec(SG, 'cat -n /etc/nginx/sites-enabled/default | tail -30')
  console.log('\n=== 末尾30行 ===')
  console.log(c2.stdout || c2.stderr)
  
  // 用grep看看/images/上下文
  const c3 = await exec(SG, 'grep -n -B5 -A10 "images" /etc/nginx/sites-enabled/default')
  console.log('\n=== /images/ 上下文 ===')
  console.log(c3.stdout || c3.stderr)

  // 看起来location被插入到错误位置了
  // 最稳妥的方法：直接用python重新生成正确的配置文件
  console.log('\n' + '═'.repeat(50))
  console.log('🔧 重新生成正确的配置')
  console.log('═'.repeat(50))

  const result = await exec(SG, `
python3 << 'PYEOF'
# 1. 读取原始模板
with open('/etc/nginx/sites-available/default', 'r') as f:
    content = f.read()

# 2. 找到第一个server块的结束位置（行号71的}）
# 通过解析大括号匹配
idx = content.index('server {')
depth = 0
pos = idx
while pos < len(content):
    if content[pos] == '{':
        depth += 1
    elif content[pos] == '}':
        depth -= 1
        if depth == 0:
            # 在这个}之前插入
            insert_block = '''
    # 铸渊图片工作室 · 代理到本地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;
    }
'''
            new_content = content[:pos] + insert_block + content[pos:]
            with open('/etc/nginx/sites-enabled/default', 'w') as f:
                f.write(new_content)
            print(f'OK: 插入成功，pos={pos}')
            break
    pos += 1
else:
    print('ERROR: 找不到server块结束位置')
PYEOF
`)
  console.log('Python:', result.stdout || result.stderr)

  // 验证
  const c4 = await exec(SG, 'grep -n -B3 -A12 "images" /etc/nginx/sites-enabled/default')
  console.log('\n验证插入位置:')
  console.log(c4.stdout || c4.stderr)
  
  const r1 = await exec(SG, 'nginx -t 2>&1')
  console.log('\nNginx测试:', r1.stdout || r1.stderr)
  
  if (!(r1.stdout || '').includes('test failed') && !(r1.stderr || '').includes('test failed')) {
    await exec(SG, 'nginx -s reload 2>&1')
    const r2 = await exec(SG, 'curl -s -w "\\nHTTP:%{http_code}" http://localhost/images/ 2>&1')
    console.log('\n验证:', r2.stdout || r2.stderr)
  } else {
    console.log('配置有误，回滚')
    await exec(SG, 'cp /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default')
  }
}

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