#!/usr/bin/env python3

def fix_nginx_config():
    config = '''user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;

    server {
        listen 80;
        server_name www.fengzhongxing.com;

        location / {
            root /usr/share/nginx/html/official;
            try_files $uri $uri/ /index.html;
        }

        location /api/ {
            proxy_pass http://api-gateway:8080/api/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }

    server {
        listen 80;
        server_name platform.fengzhongxing.com;

        location / {
            root /usr/share/nginx/html/platform;
            try_files $uri $uri/ /index.html;
        }

        location /api/ {
            proxy_pass http://api-gateway:8080/api/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }

    server {
        listen 80;
        server_name merchant.fengzhongxing.com;

        location / {
            root /usr/share/nginx/html/merchant;
            try_files $uri $uri/ /index.html;
        }

        location /api/ {
            proxy_pass http://api-gateway:8080/api/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }

    server {
        listen 8080;
        server_name api.fengzhongxing.com;

        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS, PATCH";
        add_header Access-Control-Allow-Headers "Content-Type, Authorization, token, x-request-start";

        if ($request_method = OPTIONS) {
            return 204;
        }

        location /api/ {
            proxy_pass http://api-gateway:8080/api/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
}
'''
    with open('/opt/Fzxpodman/nginx/conf/nginx.conf', 'w') as f:
        f.write(config)
    print("Simple Nginx configuration updated")

if __name__ == "__main__":
    fix_nginx_config()
