server {
    listen 80;
    server_name _;

    root /usr/share/nginx/html;
    index index.html;

    # 跨域隔离头（SharedArrayBuffer / WASM 线程模式所需）
    add_header Cross-Origin-Opener-Policy "same-origin";
    add_header Cross-Origin-Embedder-Policy "require-corp";

    # 前端静态资源
    location / {
        try_files $uri $uri/ /index.html;
    }

    # REST API 反代
    location /api/ {
        proxy_pass http://backend:8080;
        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;
    }

    # WebSocket 反代
    location /ws {
        proxy_pass http://backend:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        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_read_timeout 86400s;
        proxy_send_timeout 86400s;
    }

    # ONNX Runtime WASM 模块（.mjs 必须是 JS MIME 类型）
    location ~* \.mjs$ {
        types { }
        default_type application/javascript;
        expires 7d;
        add_header Cache-Control "public, immutable";
        add_header Cross-Origin-Opener-Policy "same-origin";
        add_header Cross-Origin-Embedder-Policy "require-corp";
    }

    # WebAssembly 二进制文件
    location ~* \.wasm$ {
        types { }
        default_type application/wasm;
        expires 7d;
        add_header Cache-Control "public, immutable";
        add_header Cross-Origin-Opener-Policy "same-origin";
        add_header Cross-Origin-Embedder-Policy "require-corp";
    }

    # ONNX 模型文件
    location ~* \.onnx$ {
        types { }
        default_type application/octet-stream;
        expires 7d;
        add_header Cache-Control "public, immutable";
    }

    # 其他静态资源缓存
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 7d;
        add_header Cache-Control "public, immutable";
    }

    # Gzip 压缩
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript application/wasm;
    gzip_min_length 256;
}
