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

import requests
import json

def validate_system():
    """验证系统各组件是否正常"""
    base_url = "http://localhost:5678"
    
    print("🔍 系统组件验证")
    print("=" * 50)
    
    tests = []
    
    # 1. 测试主页面
    try:
        response = requests.get(base_url, timeout=5)
        if response.status_code == 200:
            tests.append(("✅ 主页面", "访问正常"))
        else:
            tests.append(("❌ 主页面", f"HTTP {response.status_code}"))
    except Exception as e:
        tests.append(("❌ 主页面", str(e)))
    
    # 2. 测试测评配置页
    try:
        response = requests.get(f"{base_url}/survey.html", timeout=5)
        if response.status_code == 200:
            tests.append(("✅ 测评配置页", "访问正常"))
        else:
            tests.append(("❌ 测评配置页", f"HTTP {response.status_code}"))
    except Exception as e:
        tests.append(("❌ 测评配置页", str(e)))
    
    # 3. 测试题库API（通过API接口验证Excel数据）
    try:
        response = requests.get(f"{base_url}/api/questions", timeout=5)
        if response.status_code == 200:
            data = response.json()
            basic_count = len(data.get("基础题", []))
            advanced_count = len(data.get("进阶题", []))
            contest_count = len(data.get("竞赛题", []))
            tests.append(("✅ 题库API", f"基础题:{basic_count} 进阶题:{advanced_count} 竞赛题:{contest_count}"))
        else:
            tests.append(("❌ 题库API", f"HTTP {response.status_code}"))
    except Exception as e:
        tests.append(("❌ 题库API", str(e)))
    
    # 4. 测试创建会话API
    try:
        create_data = {
            "name": "验证测试",
            "school": "测试学校",
            "grade": "五年级",
            "selectedTag": "五年级上册1-光",
            "questionsConfig": {"基础题": 1, "进阶题": 1, "竞赛题": 1}
        }
        
        response = requests.post(f"{base_url}/api/create-session", 
                               json=create_data, 
                               timeout=5)
        if response.status_code == 200:
            result = response.json()
            session_id = result['sessionId']
            tests.append(("✅ 创建会话API", f"SessionID: {session_id[:8]}..."))
            
            # 5. 测试答题页面
            response = requests.get(f"{base_url}/quiz/{session_id}", timeout=5)
            if response.status_code == 200:
                tests.append(("✅ 答题页面", f"访问正常"))
            else:
                tests.append(("❌ 答题页面", f"HTTP {response.status_code}"))
        else:
            tests.append(("❌ 创建会话API", f"HTTP {response.status_code}"))
    except Exception as e:
        tests.append(("❌ 创建会话API", str(e)))
    
    # 6. 测试报告列表API
    try:
        response = requests.get(f"{base_url}/api/reports", timeout=5)
        if response.status_code == 200:
            data = response.json()
            tests.append(("✅ 报告列表API", f"共 {data.get('total', 0)} 个报告"))
        else:
            tests.append(("❌ 报告列表API", f"HTTP {response.status_code}"))
    except Exception as e:
        tests.append(("❌ 报告列表API", str(e)))
    
    # 显示结果
    print("\n📊 验证结果:")
    for status, description in tests:
        print(f"  {status} {description}")
    
    # 统计
    success_count = sum(1 for status, _ in tests if status.startswith("✅"))
    total_count = len(tests)
    
    print(f"\n📈 系统状态: {success_count}/{total_count} 组件正常")
    
    if success_count == total_count:
        print("\n🎉 系统完全正常！可以开始使用。")
        print("\n🚀 快速开始:")
        print("   1. 访问: http://your-server-domain/")
        print("   2. 点击'开始新的测评'")
        print("   3. 填写信息并答题")
        print("   4. 查看AI生成的报告")
    else:
        print(f"\n⚠️  系统存在问题，请检查失败的组件。")

if __name__ == "__main__":
    validate_system()