"""
测试日历API路由接口
"""

import sys
import os
import requests
import json
from datetime import date

# 添加项目路径到sys.path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))


def test_calendar_api_route():
    """测试日历API路由接口"""
    print("=== 测试日历API路由接口 ===")
    
    # API基础URL（根据实际部署情况调整）
    base_url = "http://localhost:5000"  # 假设Flask应用运行在5000端口
    api_endpoint = "/api/data_parse/get-calendar-info"
    
    # 测试用例1: 有效日期格式
    print("\n1. 测试有效日期格式:")
    test_date = "2025-01-19"
    print(f"查询日期: {test_date}")
    
    try:
        response = requests.get(f"{base_url}{api_endpoint}", params={'date': test_date})
        print(f"HTTP状态码: {response.status_code}")
        print(f"响应内容: {response.text}")
        
        if response.status_code == 200:
            result = response.json()
            if result.get('return_code') == 200:
                print("✅ API调用成功！")
                calendar_data = result.get('result', {})
                if calendar_data:
                    print(f"   - ID: {calendar_data.get('id')}")
                    print(f"   - 阳历: {calendar_data.get('yangli')}")
                    print(f"   - 阴历: {calendar_data.get('yinli')}")
                    print(f"   - 五行: {calendar_data.get('wuxing')}")
                    print(f"   - 宜: {calendar_data.get('yi')}")
                    print(f"   - 忌: {calendar_data.get('ji')}")
            else:
                print(f"❌ 业务逻辑失败: {result.get('error')}")
        else:
            print(f"❌ HTTP请求失败: {response.status_code}")
            
    except requests.exceptions.ConnectionError:
        print("❌ 连接失败 - 请确保Flask应用正在运行")
    except Exception as e:
        print(f"❌ 测试过程中发生异常: {e}")
    
    # 测试用例2: 无效日期格式
    print("\n2. 测试无效日期格式:")
    invalid_date = "2025-1-19"
    print(f"查询日期: {invalid_date}")
    
    try:
        response = requests.get(f"{base_url}{api_endpoint}", params={'date': invalid_date})
        print(f"HTTP状态码: {response.status_code}")
        print(f"响应内容: {response.text}")
        
        if response.status_code == 400:
            print("✅ 正确返回400错误状态码")
        else:
            print(f"❌ 期望400状态码，实际得到: {response.status_code}")
            
    except requests.exceptions.ConnectionError:
        print("❌ 连接失败 - 请确保Flask应用正在运行")
    except Exception as e:
        print(f"❌ 测试过程中发生异常: {e}")
    
    # 测试用例3: 缺少日期参数
    print("\n3. 测试缺少日期参数:")
    print("不传递date参数")
    
    try:
        response = requests.get(f"{base_url}{api_endpoint}")
        print(f"HTTP状态码: {response.status_code}")
        print(f"响应内容: {response.text}")
        
        if response.status_code == 400:
            print("✅ 正确返回400错误状态码")
        else:
            print(f"❌ 期望400状态码，实际得到: {response.status_code}")
            
    except requests.exceptions.ConnectionError:
        print("❌ 连接失败 - 请确保Flask应用正在运行")
    except Exception as e:
        print(f"❌ 测试过程中发生异常: {e}")
    
    # 测试用例4: 空日期参数
    print("\n4. 测试空日期参数:")
    empty_date = ""
    print(f"查询日期: '{empty_date}'")
    
    try:
        response = requests.get(f"{base_url}{api_endpoint}", params={'date': empty_date})
        print(f"HTTP状态码: {response.status_code}")
        print(f"响应内容: {response.text}")
        
        if response.status_code == 400:
            print("✅ 正确返回400错误状态码")
        else:
            print(f"❌ 期望400状态码，实际得到: {response.status_code}")
            
    except requests.exceptions.ConnectionError:
        print("❌ 连接失败 - 请确保Flask应用正在运行")
    except Exception as e:
        print(f"❌ 测试过程中发生异常: {e}")
    
    print("\n✓ 所有API路由测试完成！")


def test_api_documentation():
    """测试API文档和接口规范"""
    print("\n=== 测试API文档和接口规范 ===")
    
    # 检查API接口规范
    print("API接口规范:")
    print("- 端点: GET /api/data_parse/get-calendar-info")
    print("- 参数: date (YYYY-MM-DD格式)")
    print("- 返回格式: 标准化的JSON响应")
    
    # 检查返回字段
    print("\n返回字段说明:")
    print("- reason: 操作结果描述")
    print("- return_code: HTTP状态码")
    print("- result: 黄历信息数据对象")
    print("- error: 错误信息（失败时）")
    
    print("\n✓ API文档测试完成！")


def main():
    """主测试函数"""
    print("开始测试日历API路由接口...\n")
    
    try:
        test_api_documentation()
        test_calendar_api_route()
        
        print("\n🎉 所有测试完成！")
        print("\nAPI接口特性:")
        print("- ✅ GET方法访问")
        print("- ✅ 日期参数验证")
        print("- ✅ 标准化JSON响应")
        print("- ✅ 完整的错误处理")
        print("- ✅ 详细的日志记录")
        print("- ✅ 符合RESTful规范")
        
        print("\n使用方法:")
        print("GET /api/data_parse/get-calendar-info?date=2025-01-19")
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()
