#!/usr/bin/env python3
"""
测试灵活CORS配置的脚本
用于验证任意前端地址的跨域请求是否正常工作
"""

import requests
import json
from datetime import datetime
import random

def generate_random_origin():
    """生成随机的Origin地址用于测试"""
    # 随机IP地址
    ip_ranges = [
        "192.168.1", "192.168.2", "192.168.3", "192.168.4", "192.168.5",
        "10.0.1", "10.0.2", "10.0.3", "10.0.4", "10.0.5",
        "172.16.1", "172.16.2", "172.16.3", "172.16.4", "172.16.5"
    ]
    
    # 随机端口
    ports = [3000, 5173, 8080, 3001, 5174, 8081, 4000, 5000, 6000]
    
    ip_base = random.choice(ip_ranges)
    ip_last = random.randint(1, 254)
    port = random.choice(ports)
    
    return f"http://{ip_base}.{ip_last}:{port}"

def test_flexible_cors():
    """测试灵活的CORS配置"""
    base_url = "http://company.citupro.com:5500"
    endpoint = "/api/data_parse/get-calendar-info"
    
    print("=== 测试灵活CORS配置 ===")
    print(f"测试时间: {datetime.now()}")
    print(f"目标服务器: {base_url}")
    print(f"测试端点: {endpoint}")
    print("=" * 60)
    
    # 测试1: 测试固定Origin
    print("1. 测试固定Origin...")
    test_origins = [
        "http://localhost:5173",
        "http://192.168.3.218:5173",
        "http://10.0.0.1:3000",
        "http://172.16.1.100:8080"
    ]
    
    for origin in test_origins:
        print(f"\n   测试Origin: {origin}")
        try:
            headers = {
                'Origin': origin,
                'Access-Control-Request-Method': 'GET'
            }
            
            response = requests.options(f"{base_url}{endpoint}", headers=headers)
            print(f"   OPTIONS状态码: {response.status_code}")
            
            cors_origin = response.headers.get('Access-Control-Allow-Origin', '未设置')
            print(f"   Access-Control-Allow-Origin: {cors_origin}")
            
            if cors_origin == origin or cors_origin == '*':
                print("   ✅ CORS配置正确")
            else:
                print("   ❌ CORS配置有问题")
                
        except Exception as e:
            print(f"   ❌ 测试失败: {e}")
    
    # 测试2: 测试随机Origin
    print("\n2. 测试随机Origin...")
    for i in range(3):
        random_origin = generate_random_origin()
        print(f"\n   测试随机Origin {i+1}: {random_origin}")
        
        try:
            headers = {
                'Origin': random_origin,
                'Access-Control-Request-Method': 'GET'
            }
            
            response = requests.options(f"{base_url}{endpoint}", headers=headers)
            print(f"   OPTIONS状态码: {response.status_code}")
            
            cors_origin = response.headers.get('Access-Control-Allow-Origin', '未设置')
            print(f"   Access-Control-Allow-Origin: {cors_origin}")
            
            if cors_origin == random_origin or cors_origin == '*':
                print("   ✅ 随机Origin支持正确")
            else:
                print("   ❌ 随机Origin支持有问题")
                
        except Exception as e:
            print(f"   ❌ 测试失败: {e}")
    
    # 测试3: 测试实际GET请求
    print("\n3. 测试实际GET请求...")
    test_origin = "http://192.168.100.200:9999"  # 一个不常见的地址
    print(f"   测试Origin: {test_origin}")
    
    try:
        today = datetime.now().strftime("%Y-%m-%d")
        headers = {'Origin': test_origin}
        
        response = requests.get(f"{base_url}{endpoint}?date={today}", headers=headers)
        print(f"   GET状态码: {response.status_code}")
        
        if response.status_code == 200:
            print("   ✅ GET请求成功")
            cors_origin = response.headers.get('Access-Control-Allow-Origin', '未设置')
            print(f"   Access-Control-Allow-Origin: {cors_origin}")
        else:
            print(f"   ❌ GET请求失败: {response.text}")
            
    except Exception as e:
        print(f"   ❌ GET请求异常: {e}")
    
    print("\n" + "=" * 60)
    print("测试完成！")
    print("\n如果看到✅，说明CORS配置灵活且正确。")
    print("如果看到❌，请检查：")
    print("1. Flask应用是否已重启")
    print("2. 新的灵活CORS配置是否生效")
    print("3. 是否启用了ALLOW_ALL_ORIGINS")

if __name__ == "__main__":
    test_flexible_cors()
