/**
 * 终极方案：直接用Node.js修改default配置
 * 在服务器上运行python脚本精确插入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() {
  // 先看完整的当前配置
  const c1 = await exec(SG, 'cat -n /etc/nginx/sites-enabled/default | head -80')
  console.log('=== 完整配置(1-80) ===')
  console.log(c1.stdout || c1.stderr)
  
  const c2 = await exec(SG, 'cat -n /etc/nginx/sites-enabled/default | tail -80')
  console.log('\n=== 完整配置(末尾80行) ===')
  console.log(c2.stdout || c2.stderr)

  // 找/images/的位置
  const c3 = await exec(SG, 'grep -n "images" /etc/nginx/sites-enabled/default')
  console.log('\n=== /images/ 位置 ===')
  console.log(c3.stdout || c3.stderr)
  
  // 检查default文件是否被正确恢复
  const c4 = await exec(SG, 'head -50 /etc/nginx/sites-available/default 2>/dev/null | grep -n "server"')
  console.log('\n=== sites-available/default server位置 ===')
  console.log(c4.stdout || c4.stderr)

  // 显示默认server块
  console.log('\n=== 默认server块(第41-80行) ===')
  const c5 = await exec(SG, 'sed -n \'41,80p\' /etc/nginx/sites-enabled/default')
  console.log(c5.stdout || c5.stderr)

  // 我决定用另一种方法：删除所有修改，用python精确处理
  console.log('\n' + '═'.repeat(50))
  console.log('🔧 使用Python精确插入location块')
  console.log('═'.repeat(50))

  await exec(SG, `
python3 << 'PYEOF'
# 恢复原始配置
import shutil
shutil.copy('/etc/nginx/sites-available/default', '/etc/nginx/sites-enabled/default')

# 读取
with open('/etc/nginx/sites-enabled/default', 'r') as f:
    lines = f.readlines()

# 找到第一个 active server block (非注释的server {)
# 然后找到对应的第一个 }
server_start = None
for i, line in enumerate(lines):
    stripped = line.strip()
    if stripped == 'server {' and not line.strip().startswith('#'):
        # 这应该就是第一个非注释的server块
        server_start = i
        break

if server_start is not None:
    # 找这个server块的结束（匹配的}）
    depth = 0
    for j in range(server_start, len(lines)):
        stripped = lines[j].strip()
        # 忽略注释
        if stripped.startswith('#'):
            continue
        if '{' in stripped:
            depth += stripped.count('{')
        if '}' in stripped:
            depth -= stripped.count('}')
            if depth == 0:
                # 在}之前插入location块
                location_block = [
                    '\n',
                    '    # 铸渊图片工作室 · 代理到本地3912\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',
                    '    }\n',
                ]
                lines[j:j] = location_block
                with open('/etc/nginx/sites-enabled/default', 'w') as f:
                    f.writelines(lines)
                print(f'OK: 在第{j}行前插入location块')
                break
    else:
        print('ERROR: server block not properly closed')
else:
    print('ERROR: no active server block found')
PYEOF
`)

  // 测试
  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('验证 /images/:', r3.stdout || r3.stderr)

  // 如果还不行，换最后方案：创建文件符号链接
  if ((r3.stdout || '').includes('404') || (r3.stderr || '').includes('404')) {
    console.log('\n⚠️ 路由方案失败，使用最后方案：软链接图片目录')
    await exec(SG, 'mkdir -p /var/www/html/images')
    await exec(SG, 'ln -sf /data/image-studio/output /var/www/html/images/output 2>&1')
    await exec(SG, 'ls -la /var/www/html/images/')
    const r4 = await exec(SG, 'curl -s http://localhost/images/output/ | head -5')
    console.log('软链接测试:', r4.stdout || r4.stderr)
  }
}

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