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

"""
网络连接测试脚本
帮助诊断手机/平板连接问题
"""

import socket
import subprocess
import sys
import threading
import time
from http.server import HTTPServer, SimpleHTTPRequestHandler

def get_local_ip():
    """获取本机IP地址"""
    try:
        # 方法1: 连接到远程地址获取本地IP
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
        s.close()
        return ip
    except:
        try:
            # 方法2: 获取主机名对应的IP
            hostname = socket.gethostname()
            ip = socket.gethostbyname(hostname)
            if ip.startswith("127."):
                return None
            return ip
        except:
            return None

def test_port(host, port):
    """测试端口是否可访问"""
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(5)
        result = sock.connect_ex((host, port))
        sock.close()
        return result == 0
    except:
        return False

def start_test_server(port=8888):
    """启动测试HTTP服务器"""
    class TestHandler(SimpleHTTPRequestHandler):
        def do_GET(self):
            self.send_response(200)
            self.send_header('Content-type', 'text/html; charset=utf-8')
            self.end_headers()
            html = """
            <html><head><meta charset="utf-8"><title>网络测试</title></head>
            <body style="font-family: Arial; padding: 20px; background: #f0f0f0;">
                <h1 style="color: green;">✅ 网络连接测试成功!</h1>
                <p>如果您能看到这个页面，说明网络连接正常。</p>
                <p><strong>测试时间:</strong> %s</p>
                <p><strong>您的IP:</strong> %s</p>
                <p><a href="/">刷新测试</a></p>
            </body></html>
            """ % (time.strftime('%Y-%m-%d %H:%M:%S'), self.client_address[0])
            self.wfile.write(html.encode('utf-8'))
            
        def log_message(self, format, *args):
            print(f"📱 测试访问: {self.client_address[0]} - {format % args}")
    
    try:
        server = HTTPServer(('0.0.0.0', port), TestHandler)
        print(f"🧪 测试服务器已启动，端口: {port}")
        server.serve_forever()
    except Exception as e:
        print(f"❌ 测试服务器启动失败: {e}")

def main():
    print("=" * 60)
    print("🔍 网络连接诊断工具")
    print("=" * 60)
    print()
    
    # 1. 获取IP地址
    print("📍 1. 获取网络IP地址...")
    local_ip = get_local_ip()
    if local_ip:
        print(f"✅ 本机IP地址: {local_ip}")
    else:
        print("❌ 无法获取IP地址，请检查网络连接")
        return
    
    # 2. 检查常用端口
    print("\n🔌 2. 检查端口状态...")
    ports_to_test = [5000, 8080, 8888]
    for port in ports_to_test:
        if test_port('127.0.0.1', port):
            print(f"⚠️  端口 {port} 已被占用")
        else:
            print(f"✅ 端口 {port} 可用")
    
    # 3. 显示连接信息
    print(f"\n📱 3. 移动设备连接信息:")
    print(f"   主服务器地址: http://{local_ip}:5000")
    print(f"   手机客户端: http://{local_ip}:5000/mobile/mobile_client.html")
    print(f"   测试地址: http://{local_ip}:8888")
    
    # 4. 防火墙检查提示
    print(f"\n🛡️  4. 防火墙设置提示:")
    print("   如果平板无法连接，请检查Windows防火墙设置:")
    print("   1. 打开 Windows 安全中心")
    print("   2. 点击 防火墙和网络保护")
    print("   3. 点击 允许应用通过防火墙")
    print("   4. 确保 Python 程序被允许通过防火墙")
    print("   或者临时关闭防火墙进行测试")
    
    # 5. 网络检查命令
    print(f"\n🔧 5. 网络检查命令:")
    print(f"   在平板上ping测试: ping {local_ip}")
    print(f"   在电脑上查看网络: ipconfig")
    print(f"   检查防火墙状态: netsh advfirewall show allprofiles")
    
    # 6. 启动测试服务器
    print(f"\n🧪 6. 启动网络测试服务器...")
    print(f"   请在平板浏览器访问: http://{local_ip}:8888")
    print("   如果能看到测试页面，说明网络连接正常")
    print("   按 Ctrl+C 停止测试")
    print()
    
    try:
        start_test_server(8888)
    except KeyboardInterrupt:
        print("\n👋 测试结束")

if __name__ == "__main__":
    main() 