#!/usr/bin/env python3
"""Nginx 8443 HTTPS 설정 수정"""
import paramiko, time, sys

HOST = '101.79.17.164'; USER = 'root'; PASS = '1q2w3e!Q'
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(HOST, username=USER, password=PASS, timeout=15)
sftp = client.open_sftp()

def run(label, cmd, timeout=20):
    print(f'\n[{label}]')
    chan = client.get_transport().open_session()
    chan.set_combine_stderr(True)
    chan.exec_command(cmd)
    start = time.time()
    while not chan.exit_status_ready():
        if chan.recv_ready(): sys.stdout.buffer.write(chan.recv(4096)); sys.stdout.flush()
        if time.time() - start > timeout: break
        time.sleep(0.2)
    while chan.recv_ready(): sys.stdout.buffer.write(chan.recv(4096))
    sys.stdout.flush()
    chan.recv_exit_status()

guardia_https = r"""server {
    listen 8443 ssl;
    server_name _;
    ssl_certificate     /etc/ssl/guardia/server.crt;
    ssl_certificate_key /etc/ssl/guardia/server.key;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;
    client_max_body_size 100M;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options DENY always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-XSS-Protection "1; mode=block" always;
    location / {
        proxy_pass         http://127.0.0.1:8001;
        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 https;
        proxy_read_timeout 300s;
    }
    location /api/ {
        limit_req zone=guardia_api burst=10 nodelay;
        proxy_pass         http://127.0.0.1:8001;
        proxy_http_version 1.1;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-Proto https;
        proxy_read_timeout 60s;
    }
    location /ws/ {
        proxy_pass         http://127.0.0.1:8001;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection "upgrade";
        proxy_read_timeout 3600s;
    }
}
"""

with sftp.open('/etc/nginx/sites-available/guardia-https', 'w') as f:
    f.write(guardia_https)
sftp.close()

run('Nginx 설정 검증', 'nginx -t')
run('Nginx 리로드', 'systemctl reload nginx && echo NGINX_OK')
time.sleep(2)
run('HTTPS 8443 테스트', 'curl -sk https://localhost:8443/api/external/health -w " HTTP %{http_code}"')
run('CORS 테스트 (HTTPS)',
    'curl -sk -I -X OPTIONS https://localhost:8443/api/external/health '
    '-H "Origin: https://portal.myorg.go.kr" | grep -i access-control')

client.close()
print('\n완료')
