/**
 * 查看Python插入结果 + 直接手动处理
 */

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() {
  // 检查/images/是否在配置中
  console.log('=== 查找/images/ ===')
  const c1 = await exec(SG, 'grep -n "images" /etc/nginx/sites-enabled/default')
  console.log(c1.stdout || c1.stderr || '(无匹配)')

  console.log('\n=== 查找location ===')
  const c2 = await exec(SG, 'grep -n "location" /etc/nginx/sites-enabled/default')
  console.log(c2.stdout || c2.stderr)

  // 检查整个server块
  console.log('\n=== 完整server块(19-75行) ===')
  const c3 = await exec(SG, 'sed -n \'19,75p\' /etc/nginx/sites-enabled/default')
  console.log(c3.stdout || c3.stderr)

  // 直接写入一个新文件到conf.d (最干净的方法)
  console.log('\n' + '═'.repeat(50))
  console.log('🔧 直接写入conf.d配置文件')
  console.log('═'.repeat(50))
  
  // 创建一个单独的配置文件，监听在端口80，只处理/images/路径
  // 使用server_name _ 如果冲突，就用default_server的配置
  // 实际上，我们直接把这个location加到存在的default server里最简单
  // 用exec直接sed插入
  
  const sedScript = `sed -i '71i\\\\n    # 铸渊图片工作室\n    location /images/ {\\n        proxy_pass http://127.0.0.1:3912/;\\n        proxy_http_version 1.1;\\n        proxy_set_header Host \\$host;\\n        proxy_set_header X-Real-IP \\$remote_addr;\\n        proxy_set_header X-Forwarded-For \\$proxy_add_x_forwarded_for;\\n        proxy_set_header X-Forwarded-Proto \\$scheme;\\n        proxy_buffering off;\\n        proxy_read_timeout 60s;\\n    }' /etc/nginx/sites-enabled/default`
  
  console.log('执行sed插入...')
  const r1 = await exec(SG, sedScript)
  console.log('sed:', (r1.stdout || r1.stderr || 'ok').slice(0, 200))

  const r2 = await exec(SG, 'grep -n "images" /etc/nginx/sites-enabled/default')
  console.log('验证:', r2.stdout || r2.stderr || '(无匹配)')

  // 如果sed不行，直接用Python写文件内容
  const c4 = await exec(SG, 'cat /etc/nginx/sites-enabled/default')
  const content = c4.stdout || ''
  if (content && !content.includes('/images/')) {
    console.log('\n⚠️ sed失败，用Python精确写入...')
    
    const result = await exec(SG, `
python3 << 'PYEOF'
with open('/etc/nginx/sites-enabled/default', 'r') as f:
    content = f.read()

# 在第71行位置（第一个server块结束时）插入
# 找第一个独立的 "}" 在非注释行
lines = content.split('\\n')
for i, line in enumerate(lines):
    stripped = line.strip()
    # 找到第一个server块的结束 - 找第一个单独的 }
    # 在注释外的、不在server块开头的 }
    if stripped == '}' and i > 20 and i < 75:
        insert = [
            '',
            '    # 铸渊图片工作室 · 代理到本地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;',
            '    }',
        ]
        lines[i:i] = insert
        content = '\\n'.join(lines)
        with open('/etc/nginx/sites-enabled/default', 'w') as f:
            f.write(content)
        print(f'OK: 在第{i}行前插入location块')
        break
else:
    print('ERROR: 找不到合适的插入位置')
PYEOF
`)
    console.log('Python:', result.stdout || result.stderr)
  }

  const r3 = await exec(SG, 'grep -n "images" /etc/nginx/sites-enabled/default')
  console.log('\n验证:', r3.stdout || r3.stderr || '(无匹配)')

  const r4 = await exec(SG, 'nginx -t 2>&1')
  console.log('Nginx测试:', r4.stdout || r4.stderr)
  
  if ((r4.stdout || '').includes('test failed') || (r4.stderr || '').includes('test failed')) {
    console.log('\n⚠️ 配置有问题，回滚...')
    await exec(SG, 'cp /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default')
    await exec(SG, 'nginx -t 2>&1')
    console.log('已回滚')
    return
  }

  const r5 = await exec(SG, 'nginx -s reload 2>&1')
  console.log('重载:', r5.stdout || r5.stderr || 'ok')
  
  const r6 = await exec(SG, 'curl -s -w "\\nHTTP_CODE:%{http_code}" http://localhost/images/ | tail -5')
  console.log('\n验证:', r6.stdout || r6.stderr)
  
  const r7 = await exec(SG, 'curl -s -w "\\nHTTP_CODE:%{http_code}" http://localhost:3912/ | tail -5')
  console.log('直接3912:', r7.stdout || r7.stderr)
}

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