import paramiko
import time

host = '8.140.221.49'
username = 'root'
private_key_path = r'C:\Users\FZX\.ssh\FzxBdsh-ECS.pem'

def run_command(ssh, cmd, timeout=60):
    stdin, stdout, stderr = ssh.exec_command(cmd, timeout=timeout)
    return stdout.read().decode().strip(), stderr.read().decode().strip()

print('='*80)
print('风七六平台 - 阿里云开发环境完整修复')
print('='*80)

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:
    ssh.connect(host, username=username, key_filename=private_key_path, timeout=30)
    print('✅ SSH连接成功')
    
    print('\n' + '='*80)
    print('1. 创建Nginx配置目录和文件')
    print('='*80)
    
    nginx_conf = '''user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/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;

    gzip on;
    gzip_disable "msie6";

    server {
        listen 80;
        server_name localhost;

        location / {
            proxy_pass http://api-gateway: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;
        }

        location /health {
            return 200 "OK";
        }
    }

    server {
        listen 80;
        server_name user.localhost;

        location / {
            alias /usr/share/nginx/html/user/;
            index index.html;
            try_files $uri $uri/ /index.html =404;
        }
    }

    server {
        listen 80;
        server_name merchant.localhost;

        location / {
            alias /usr/share/nginx/html/merchant/;
            index index.html;
            try_files $uri $uri/ /index.html =404;
        }
    }

    server {
        listen 80;
        server_name rider.localhost;

        location / {
            alias /usr/share/nginx/html/rider/;
            index index.html;
            try_files $uri $uri/ /index.html =404;
        }
    }

    server {
        listen 80;
        server_name platform.localhost;

        location / {
            alias /usr/share/nginx/html/platform/;
            index index.html;
            try_files $uri $uri/ /index.html =404;
        }
    }

    server {
        listen 80;
        server_name official.localhost;

        location / {
            alias /usr/share/nginx/html/official/;
            index index.html;
            try_files $uri $uri/ /index.html =404;
        }
    }
}
'''
    
    run_command(ssh, 'mkdir -p /opt/Fzxpodman/infrastructure/nginx/conf')
    sftp = ssh.open_sftp()
    with sftp.file('/opt/Fzxpodman/infrastructure/nginx/conf/nginx.conf', 'w') as f:
        f.write(nginx_conf)
    sftp.close()
    print('✅ Nginx配置文件已创建')
    
    print('\n' + '='*80)
    print('2. 创建前端入口文件')
    print('='*80)
    
    index_html = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>风七六平台 - {title}</title>
    <style>
        body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; text-align: center; padding: 50px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }}
        .container {{ background: white; padding: 40px; border-radius: 12px; box-shadow: 0 10px 40px rgba(0,0,0,0.1); max-width: 600px; margin: 0 auto; }}
        h1 {{ color: #067bff; margin-bottom: 20px; }}
        p {{ color: #666; line-height: 1.6; }}
        .status {{ display: inline-block; padding: 8px 16px; border-radius: 20px; font-weight: bold; margin-top: 20px; }}
        .status.ok {{ background: #d4edda; color: #155724; }}
        .env {{ margin-top: 20px; padding: 10px; background: #f8f9fa; border-radius: 6px; font-family: monospace; }}
    </style>
</head>
<body>
    <div class="container">
        <h1>🚀 风七六{title}</h1>
        <p>服务已成功部署到阿里云开发环境</p>
        <div class="status ok">✅ 服务运行正常</div>
        <div class="env">环境: aliyun-dev | 时间: {time}</div>
    </div>
</body>
</html>
'''
    
    import datetime
    current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    run_command(ssh, 'mkdir -p /opt/Fzxpodman/infrastructure/nginx/html/{user,merchant,rider,platform,official}')
    
    sftp = ssh.open_sftp()
    with sftp.file('/opt/Fzxpodman/infrastructure/nginx/html/user/index.html', 'w') as f:
        f.write(index_html.format(title='用户端', time=current_time))
    with sftp.file('/opt/Fzxpodman/infrastructure/nginx/html/merchant/index.html', 'w') as f:
        f.write(index_html.format(title='商家端', time=current_time))
    with sftp.file('/opt/Fzxpodman/infrastructure/nginx/html/rider/index.html', 'w') as f:
        f.write(index_html.format(title='骑手端', time=current_time))
    with sftp.file('/opt/Fzxpodman/infrastructure/nginx/html/platform/index.html', 'w') as f:
        f.write(index_html.format(title='平台管理端', time=current_time))
    with sftp.file('/opt/Fzxpodman/infrastructure/nginx/html/official/index.html', 'w') as f:
        f.write(index_html.format(title='官方网站', time=current_time))
    sftp.close()
    print('✅ 前端入口文件已创建')
    
    print('\n' + '='*80)
    print('3. 重启Nginx容器')
    print('='*80)
    output, error = run_command(ssh, 'podman rm -f fzx-aliyun-nginx')
    print('删除旧容器:', output)
    
    output, error = run_command(ssh, 'cd /opt/Fzxpodman/infrastructure/compose && podman-compose -f podman-compose.aliyun-dev.yml up -d nginx')
    print('启动Nginx:', '成功' if not error else f'失败: {error}')
    
    print('\n' + '='*80)
    print('4. 重启Upload Service')
    print('='*80)
    output, error = run_command(ssh, 'podman rm -f fzx-aliyun-upload-service')
    print('删除旧容器:', output)
    
    output, error = run_command(ssh, 'cd /opt/Fzxpodman/infrastructure/compose && podman-compose -f podman-compose.aliyun-dev.yml up -d upload-service')
    print('启动Upload Service:', '成功' if not error else f'失败: {error}')
    
    print('\n' + '='*80)
    print('5. 等待服务启动...')
    print('='*80)
    time.sleep(30)
    
    print('\n' + '='*80)
    print('6. 验证容器状态')
    print('='*80)
    output, error = run_command(ssh, 'podman ps --format "table {{.Names}}\t{{.Status}}"')
    print(output)
    
    print('\n' + '='*80)
    print('7. 测试API Gateway')
    print('='*80)
    output, error = run_command(ssh, 'curl -s http://localhost:8080/actuator/health')
    print('API Gateway响应:', output[:200])
    
    print('\n' + '='*80)
    print('8. 测试Nginx')
    print('='*80)
    output, error = run_command(ssh, 'curl -s http://localhost/health')
    print('Nginx健康检查:', output)
    
    print('\n' + '='*80)
    print('9. 测试前端页面')
    print('='*80)
    output, error = run_command(ssh, 'curl -s http://localhost/user/ | head -5')
    print('用户端页面:', '正常' if '风七六' in output else '异常')
    
finally:
    ssh.close()

print('\n' + '='*80)
print('修复完成!')
print('='*80)