#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
简化版HTTPS Web服务器
使用Python内置ssl模块，无需额外依赖
"""

import ssl
import socket
from src.web_server import create_app
from get_ip import get_local_ip

def create_simple_ssl_context():
    """创建简单的SSL上下文，使用自签名证书"""
    context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    
    # 检查是否存在SSL证书文件
    import os
    cert_file = "ssl/cert.pem"
    key_file = "ssl/key.pem"
    
    if not os.path.exists(cert_file) or not os.path.exists(key_file):
        print("❌ SSL证书文件不存在")
        print("📝 为了使用HTTPS，请选择以下选项之一：")
        print("   1. 安装cryptography库: pip install cryptography")
        print("   2. 使用HTTP版本: python main_web.py")
        print("   3. 手动创建SSL证书")
        return None
    
    try:
        context.load_cert_chain(cert_file, key_file)
        return context
    except Exception as e:
        print(f"❌ 加载SSL证书失败: {e}")
        return None

def main():
    """启动简化版HTTPS服务器"""
    print("🚀 启动简化版HTTPS服务器...")
    
    # 创建Flask应用
    app = create_app()
    
    # 获取本地IP
    local_ip = get_local_ip()
    
    print(f"🌐 本地IP地址: {local_ip}")
    print()
    print("📱 访问地址:")
    print(f"   桌面端: https://127.0.0.1:5000")
    print(f"   手机端: https://{local_ip}:5000/mobile/mobile_client.html")
    print()
    print("⚠️  如果看到安全警告，请点击 '高级' -> '继续访问'")
    print()
    
    # 创建SSL上下文
    ssl_context = create_simple_ssl_context()
    
    if ssl_context is None:
        print("🔄 回退到HTTP模式...")
        print(f"   桌面端: http://127.0.0.1:5000")
        print(f"   手机端: http://{local_ip}:5000/mobile/mobile_client.html")
        app.run(host='0.0.0.0', port=5000, debug=True)
    else:
        print("🔒 HTTPS模式启动成功!")
        app.run(host='0.0.0.0', port=5000, debug=True, ssl_context=ssl_context)

if __name__ == "__main__":
    main() 