import paramiko
import datetime
import os

ECS_HOST = '8.140.221.49'
SSH_USER = 'root'
SSH_KEY_PATH = r'C:\Users\FZX\.ssh\FzxBdsh-ECS.pem'

DOMAINS = {
    'api': 'api.fengzhongxing.com',
    'nacos': 'nacos.fengzhongxing.com',
    'jenkins': 'jenkins.fengzhongxing.com',
    'platform': 'platform.fengzhongxing.com',
    'merchant': 'merchant.fengzhongxing.com',
    'rider': 'rider.fengzhongxing.com',
    'h5': 'h5.fengzhongxing.com',
    'www': 'www.fengzhongxing.com',
    'monitor': 'monitor.fengzhongxing.com',
}

LOCAL_HOSTS_PATH = r'C:\Windows\System32\drivers\etc\hosts' if os.name == 'nt' else '/etc/hosts'

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

def generate_hosts_content(ip):
    lines = []
    lines.append(f'\n# ============================================================')
    lines.append(f'# Fzx Platform - Aliyun Dev Environment ({datetime.datetime.now().strftime("%Y-%m-%d")})')
    lines.append(f'# ============================================================')
    for name, domain in DOMAINS.items():
        lines.append(f'{ip}    {domain}')
    lines.append('# ============================================================')
    return '\n'.join(lines)

def update_local_hosts(ip):
    if os.name != 'nt':
        print('  ⚠️ 非Windows系统，跳过本地hosts更新')
        return
    
    try:
        with open(LOCAL_HOSTS_PATH, 'r', encoding='utf-8') as f:
            content = f.read()
        
        marker_start = '# ============================================================'
        marker_end = '# ============================================================'
        
        if marker_start in content:
            start_idx = content.find(marker_start)
            end_idx = content.find(marker_end, start_idx + 1)
            if end_idx > start_idx:
                new_content = content[:start_idx] + generate_hosts_content(ip) + content[end_idx + len(marker_end):]
            else:
                new_content = content + '\n' + generate_hosts_content(ip)
        else:
            new_content = content + '\n' + generate_hosts_content(ip)
        
        with open(LOCAL_HOSTS_PATH, 'w', encoding='utf-8') as f:
            f.write(new_content)
        print('  ✅ 本地hosts文件已更新')
    except PermissionError:
        print('  ⚠️ 需要管理员权限更新hosts文件，请以管理员身份运行')
    except Exception as e:
        print(f'  ❌ 更新hosts失败: {e}')

def main():
    print('='*80)
    print('Fzx Platform - 域名配置工具（大厂标准：域名+反向代理）')
    print('='*80)

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    try:
        ssh.connect(ECS_HOST, username=SSH_USER, key_filename=SSH_KEY_PATH, timeout=30)
        print(f'\n✅ 已连接到 {ECS_HOST}')
    except Exception as e:
        print(f'❌ SSH连接失败: {e}')
        return

    print('\n1. 生成hosts文件内容')
    hosts_content = generate_hosts_content(ECS_HOST)
    print(hosts_content)
    
    print('\n2. 更新本地hosts文件')
    update_local_hosts(ECS_HOST)
    
    print('\n3. 验证域名访问')
    import time
    time.sleep(2)
    
    test_urls = [
        ('nacos.fengzhongxing.com', '/nacos/v1/ns/health'),
        ('jenkins.fengzhongxing.com', '/jenkins/'),
        ('api.fengzhongxing.com', '/health'),
        ('www.fengzhongxing.com', '/'),
    ]
    
    print('\n域名访问测试结果:')
    print('-' * 60)
    for domain, path in test_urls:
        output, error = run_command(ssh, f'curl -s -o /dev/null -w "%{{http_code}}" -H "Host: {domain}" http://localhost{path}')
        status = '✅' if output == '200' else '❌'
        print(f'{status} {domain}{path}: HTTP {output}')

    ssh.close()

    print('\n' + '='*80)
    print('域名配置完成!')
    print('='*80)
    
    print('\n📋 hosts文件内容（如需手动添加）:')
    print(hosts_content)

if __name__ == '__main__':
    main()
