#!/usr/bin/env python3
"""
测试新IP地址的CORS配置
用于验证192.168.3.218:5173的跨域请求是否正常工作
"""

import requests
import json
from datetime import datetime

def test_cors_new_ip():
    """测试新IP地址的CORS配置"""
    base_url = "http://company.citupro.com:5500"
    endpoint = "/api/data_parse/get-calendar-info"
    
    print("=== 测试新IP地址的CORS配置 ===")
    print(f"测试时间: {datetime.now()}")
    print(f"目标服务器: {base_url}")
    print(f"测试端点: {endpoint}")
    print(f"模拟前端: http://192.168.3.218:5173")
    print("=" * 60)
    
    # 测试1: OPTIONS预检请求
    print("1. 测试OPTIONS预检请求...")
    try:
        headers = {
            'Origin': 'http://192.168.3.218:5173',
            'Access-Control-Request-Method': 'GET',
            'Access-Control-Request-Headers': 'Content-Type'
        }
        
        response = requests.options(f"{base_url}{endpoint}", headers=headers)
        print(f"   状态码: {response.status_code}")
        
        # 检查CORS头部
        cors_headers = []
        for key, value in response.headers.items():
            if key.lower().startswith('access-control'):
                cors_headers.append(f"{key}: {value}")
        
        if cors_headers:
            print("   CORS头部:")
            for header in cors_headers:
                print(f"     {header}")
        else:
            print("   ❌ 未找到CORS头部")
            
    except Exception as e:
        print(f"   ❌ 预检请求失败: {e}")
    
    print()
    
    # 测试2: 实际GET请求
    print("2. 测试实际GET请求...")
    try:
        today = datetime.now().strftime("%Y-%m-%d")
        headers = {'Origin': 'http://192.168.3.218:5173'}
        
        response = requests.get(f"{base_url}{endpoint}?date={today}", headers=headers)
        print(f"   状态码: {response.status_code}")
        
        if response.status_code == 200:
            print("   ✅ 请求成功")
            # 检查响应中的CORS头部
            cors_headers = []
            for key, value in response.headers.items():
                if key.lower().startswith('access-control'):
                    cors_headers.append(f"{key}: {value}")
            
            if cors_headers:
                print("   CORS头部:")
                for header in cors_headers:
                    print(f"     {header}")
            else:
                print("   ⚠️  响应中未找到CORS头部")
        else:
            print(f"   ❌ 请求失败: {response.text}")
            
    except Exception as e:
        print(f"   ❌ GET请求失败: {e}")
    
    print()
    
    # 测试3: 检查Origin头部设置
    print("3. 检查Origin头部设置...")
    try:
        today = datetime.now().strftime("%Y-%m-%d")
        headers = {'Origin': 'http://192.168.3.218:5173'}
        
        response = requests.get(f"{base_url}{endpoint}?date={today}", headers=headers)
        
        origin_header = response.headers.get('Access-Control-Allow-Origin', '未设置')
        print(f"   Access-Control-Allow-Origin: {origin_header}")
        
        if origin_header == 'http://192.168.3.218:5173':
            print("   ✅ Origin头部设置正确")
        elif origin_header == 'http://localhost:5173':
            print("   ⚠️  Origin头部回退到默认值")
        else:
            print(f"   ❌ Origin头部设置异常: {origin_header}")
            
    except Exception as e:
        print(f"   ❌ 检查Origin头部失败: {e}")
    
    print()
    print("=" * 60)
    print("测试完成！")
    print("\n如果看到正确的CORS头部，说明配置成功。")
    print("如果仍有问题，请检查：")
    print("1. Flask应用是否已重启")
    print("2. 新的CORS配置是否生效")
    print("3. 前端请求的Origin头部是否正确")

if __name__ == "__main__":
    test_cors_new_ip()
