#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
前端导航测试脚本
测试所有页面路由是否正常工作
"""

import requests
import sys
import time

def test_page_routes(base_url="http://localhost:5000"):
    """测试所有页面路由"""

    # 测试的路由列表
    routes = [
        ("/", "仪表板"),
        ("/dashboard", "仪表板"),
        ("/alerts", "预警管理"),
        ("/chat", "智能对话"),
        ("/chat-http", "HTTP对话")
    ]

    print("🔍 开始测试前端路由...")
    print(f"📍 基础URL: {base_url}")
    print("-" * 60)

    results = []

    for route, name in routes:
        try:
            url = f"{base_url}{route}"
            print(f"🧪 测试路由: {route} ({name})")

            # 发送请求
            response = requests.get(url, timeout=10)

            # 检查响应状态
            if response.status_code == 200:
                print(f"  ✅ 状态码: {response.status_code}")

                # 检查响应内容是否包含HTML
                content_type = response.headers.get('Content-Type', '')
                if 'text/html' in content_type:
                    print(f"  ✅ 内容类型: {content_type}")

                    # 检查是否包含导航栏
                    if 'navbar' in response.text:
                        print(f"  ✅ 导航栏: 存在")
                    else:
                        print(f"  ⚠️  导航栏: 缺失")

                    # 检查页面大小
                    size_kb = len(response.content) / 1024
                    print(f"  ✅ 页面大小: {size_kb:.1f} KB")

                    results.append((route, name, "成功", response.status_code))
                else:
                    print(f"  ❌ 内容类型错误: {content_type}")
                    results.append((route, name, "内容类型错误", response.status_code))
            else:
                print(f"  ❌ 状态码错误: {response.status_code}")
                results.append((route, name, "状态码错误", response.status_code))

        except requests.exceptions.ConnectionError:
            print(f"  ❌ 连接失败: 服务器未启动")
            results.append((route, name, "连接失败", 0))
            break
        except requests.exceptions.Timeout:
            print(f"  ❌ 请求超时")
            results.append((route, name, "请求超时", 0))
        except Exception as e:
            print(f"  ❌ 未知错误: {str(e)}")
            results.append((route, name, f"错误: {str(e)}", 0))

        print()

    # 打印测试总结
    print("=" * 60)
    print("📊 测试总结:")

    success_count = 0
    total_count = len(results)

    for route, name, status, code in results:
        status_icon = "✅" if status == "成功" else "❌"
        print(f"  {status_icon} {route} ({name}): {status}")
        if status == "成功":
            success_count += 1

    print()
    print(f"📈 成功率: {success_count}/{total_count} ({success_count/total_count*100:.1f}%)")

    if success_count == total_count:
        print("🎉 所有路由测试通过！")
        return True
    else:
        print("⚠️  部分路由存在问题")
        return False

if __name__ == "__main__":
    print("TSP助手前端路由测试工具")
    print("=" * 60)

    # 检查服务器是否运行
    base_url = "http://localhost:5000"

    # 如果提供了命令行参数，使用自定义URL
    if len(sys.argv) > 1:
        base_url = sys.argv[1]

    success = test_page_routes(base_url)

    if not success:
        print("\n💡 解决建议:")
        print("1. 确保Flask服务器已启动: python src/web/app.py")
        print("2. 检查端口是否正确: 默认5000")
        print("3. 检查防火墙设置")
        print("4. 查看服务器日志了解详细错误信息")

    sys.exit(0 if success else 1)