#!/usr/bin/env python3
"""
前后端集成测试脚本
"""
import requests
import json
import time

def test_backend_api():
    """测试后端API"""
    base_url = "http://localhost:8000"

    print("🧪 测试后端API...")

    # 1. 健康检查
    try:
        response = requests.get(f"{base_url}/health")
        print(f"✅ 健康检查: {response.json()}")
    except Exception as e:
        print(f"❌ 健康检查失败: {e}")
        return False

    # 2. 登录测试
    login_data = {"username": "testuser", "password": "123456"}
    try:
        response = requests.post(f"{base_url}/api/v1/auth/login", json=login_data)
        if response.status_code == 200:
            data = response.json()
            print(f"✅ 登录成功: {data['message']}")
            print(f"   用户ID: {data['data']['user']['id']}")
            print(f"   用户名: {data['data']['user']['username']}")
            print(f"   角色: {data['data']['user']['role']}")

            # 保存token用于后续测试
            global access_token, refresh_token
            access_token = data['data']['token']['access_token']
            refresh_token = data['data']['token']['refresh_token']
            return True
        else:
            print(f"❌ 登录失败: {response.text}")
            return False
    except Exception as e:
        print(f"❌ 登录请求失败: {e}")
        return False

def test_frontend_proxy():
    """测试前端代理配置"""
    base_url = "http://localhost:3001"

    print("\n🌐 测试前端代理...")

    # 1. 检查前端是否可访问
    try:
        response = requests.get(base_url)
        if response.status_code == 200:
            print("✅ 前端页面可访问")
        else:
            print(f"❌ 前端页面访问失败: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ 前端页面访问失败: {e}")
        return False

    # 2. 测试前端代理到后端的API调用
    try:
        # 通过前端代理调用后端API
        headers = {"Content-Type": "application/json"}
        response = requests.post(f"{base_url}/api/v1/auth/login", json={"username": "testuser", "password": "123456"}, headers=headers)

        if response.status_code == 200:
            data = response.json()
            print("✅ 前端代理API调用成功")
            print(f"   响应数据: {data}")
            return True
        else:
            print(f"❌ 前端代理API调用失败: {response.status_code}")
            print(f"   响应: {response.text}")
            return False
    except Exception as e:
        print(f"❌ 前端代理API调用失败: {e}")
        return False

def test_token_refresh():
    """测试token刷新"""
    global access_token, refresh_token

    if not access_token or not refresh_token:
        print("❌ 没有可用的token进行刷新测试")
        return False

    print("\n🔄 测试token刷新...")

    try:
        refresh_data = {"refresh_token": refresh_token}
        response = requests.post("http://localhost:8000/api/v1/auth/refresh", json=refresh_data)

        if response.status_code == 200:
            data = response.json()
            print("✅ Token刷新成功")
            print(f"   新token: {data['data']['access_token'][:50]}...")
            return True
        else:
            print(f"❌ Token刷新失败: {response.text}")
            return False
    except Exception as e:
        print(f"❌ Token刷新请求失败: {e}")
        return False

def main():
    """主测试函数"""
    print("🚀 开始前后端集成测试")
    print("=" * 50)

    # 测试后端API
    if not test_backend_api():
        print("❌ 后端API测试失败，终止测试")
        return False

    # 测试前端代理
    if not test_frontend_proxy():
        print("❌ 前端代理测试失败")
        return False

    # 测试token刷新
    if not test_token_refresh():
        print("❌ Token刷新测试失败")
        return False

    print("\n" + "=" * 50)
    print("🎉 所有测试通过！前后端集成成功！")
    return True

if __name__ == "__main__":
    main()
