"""
直接测试模板管理API端点
不需要浏览器，通过HTTP请求测试
"""

import requests
import os
import json
from datetime import datetime

BASE_URL = "http://localhost:8000"
API_BASE = f"{BASE_URL}/fs-ai-asistant/api/workflow/lawrisk"

def test_api_endpoints():
    """测试模板相关的API端点"""

    print("=" * 60)
    print("Template Management API Test")
    print("=" * 60)

    # 测试1: 获取模板元数据
    print("\n[1/5] Getting template metadata...")
    try:
        response = requests.get(f"{API_BASE}/admin/templates/permit")
        print(f"    Status: {response.status_code}")

        if response.status_code == 200:
            data = response.json()
            print(f"    Success! Response data:")
            print(f"    {json.dumps(data, indent=2, ensure_ascii=False)}")
        else:
            print(f"    Failed: {response.text}")
    except Exception as e:
        print(f"    Error: {e}")

    # 测试2: 下载模板
    print("\n[2/5] Downloading template...")
    try:
        response = requests.get(f"{API_BASE}/admin/permit-import/template")
        print(f"    Status: {response.status_code}")

        if response.status_code == 200:
            filename = "api_downloaded_template.xlsx"
            with open(filename, 'wb') as f:
                f.write(response.content)
            print(f"    Success! Downloaded {len(response.content)} bytes to {filename}")
        else:
            print(f"    Failed: {response.text}")
    except Exception as e:
        print(f"    Error: {e}")

    # 测试3: 检查目录
    print("\n[3/5] Checking template directory...")
    template_dir = "data/template"
    if os.path.exists(template_dir):
        files = os.listdir(template_dir)
        print(f"    Files in {template_dir}:")
        for f in files:
            size = os.path.getsize(os.path.join(template_dir, f))
            print(f"      - {f} ({size} bytes)")
    else:
        print(f"    Directory {template_dir} not found")

    # 测试4: 检查测试文件
    print("\n[4/5] Checking test files...")
    test_files = [
        "RiskTemplate_Test.xlsx",
        "RiskTemplate_Original.xlsx"
    ]

    for f in test_files:
        if os.path.exists(f):
            size = os.path.getsize(f)
            print(f"    Found: {f} ({size} bytes)")
        else:
            print(f"    Missing: {f}")

    # 测试5: 模拟上传（使用session）
    print("\n[5/5] Testing upload with session...")
    try:
        session = requests.Session()

        # 先检查登录状态
        response = session.get(f"{BASE_URL}/auth/me")
        print(f"    Auth check status: {response.status_code}")

        if response.status_code == 200:
            user_data = response.json()
            print(f"    Logged in as: {user_data.get('user', {}).get('username', 'unknown')}")

            # 尝试上传测试文件
            if os.path.exists("RiskTemplate_Test.xlsx"):
                with open("RiskTemplate_Test.xlsx", 'rb') as f:
                    files = {'file': f}
                    upload_response = session.post(
                        f"{API_BASE}/admin/templates/permit",
                        files=files
                    )
                    print(f"    Upload status: {upload_response.status_code}")

                    if upload_response.status_code == 200:
                        print(f"    Upload successful!")
                        print(f"    Response: {upload_response.json()}")
                    else:
                        print(f"    Upload failed: {upload_response.text}")
            else:
                print(f"    Test file not found, skipping upload")
        else:
            print(f"    Not logged in (this is expected)")
            print(f"    To test upload manually, please:")
            print(f"    1. Login at {BASE_URL}/fs-ai-asistant/api/workflow/lawrisk/login")
            print(f"    2. Then run this script again")
    except Exception as e:
        print(f"    Error: {e}")

    print("\n" + "=" * 60)
    print("API Test Complete")
    print("=" * 60)

if __name__ == "__main__":
    test_api_endpoints()
