#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
簡化API測試腳本
"""

import requests
import json
import time

def test_api_endpoints():
    """測試API端點"""
    
    print("=== API Testing ===")
    
    # 使用已經存在的Flask應用（如果正在運行）
    base_url = 'http://127.0.0.1:5000'
    
    results = []
    
    # 測試1: 健康檢查
    print("\n1. Testing health check...")
    try:
        response = requests.get(f'{base_url}/health', timeout=5)
        if response.status_code == 200:
            print("   Health check: PASS")
            results.append(('Health Check', True))
        else:
            print(f"   Health check: FAIL ({response.status_code})")
            results.append(('Health Check', False))
    except Exception as e:
        print(f"   Health check: FAIL - {e}")
        results.append(('Health Check', False))
    
    # 測試2: 認證API - 無效用戶
    print("\n2. Testing invalid login...")
    try:
        login_data = {
            'username': 'invalid@test.com',
            'password': 'wrongpassword'
        }
        response = requests.post(f'{base_url}/api/v1/auth/login', 
                               json=login_data, timeout=10)
        
        if response.status_code in [401, 404]:
            print("   Invalid login rejection: PASS")
            results.append(('Invalid Login Rejection', True))
        else:
            print(f"   Invalid login rejection: FAIL ({response.status_code})")
            results.append(('Invalid Login Rejection', False))
    except Exception as e:
        print(f"   Invalid login test: FAIL - {e}")
        results.append(('Invalid Login Rejection', False))
    
    # 測試3: 認證API - 有效用戶（如果能連接到LDAP）
    print("\n3. Testing valid login...")
    try:
        login_data = {
            'username': 'ymirliu@panjit.com.tw',
            'password': 'ˇ3EDC4rfv5tgb'
        }
        response = requests.post(f'{base_url}/api/v1/auth/login', 
                               json=login_data, timeout=15)
        
        if response.status_code == 200:
            result = response.json()
            if result.get('success'):
                print("   Valid login: PASS")
                results.append(('Valid Login', True))
                
                # 測試4: 取得當前用戶
                print("\n4. Testing current user API...")
                try:
                    me_response = requests.get(f'{base_url}/api/v1/auth/me', 
                                             cookies=response.cookies, timeout=5)
                    
                    if me_response.status_code == 200:
                        me_result = me_response.json()
                        if me_result.get('success'):
                            print("   Get current user: PASS")
                            results.append(('Get Current User', True))
                        else:
                            print("   Get current user: FAIL (invalid response)")
                            results.append(('Get Current User', False))
                    else:
                        print(f"   Get current user: FAIL ({me_response.status_code})")
                        results.append(('Get Current User', False))
                        
                except Exception as e:
                    print(f"   Get current user: FAIL - {e}")
                    results.append(('Get Current User', False))
                    
            else:
                print(f"   Valid login: FAIL - {result.get('message', 'Unknown error')}")
                results.append(('Valid Login', False))
        else:
            print(f"   Valid login: FAIL ({response.status_code})")
            try:
                error_info = response.json()
                print(f"   Error: {error_info.get('message', 'Unknown error')}")
            except:
                print(f"   Response: {response.text}")
            results.append(('Valid Login', False))
            
    except Exception as e:
        print(f"   Valid login test: FAIL - {e}")
        results.append(('Valid Login', False))
    
    # 結果總結
    print("\n=== Test Summary ===")
    passed = 0
    for test_name, success in results:
        status = "PASS" if success else "FAIL"
        print(f"{test_name}: {status}")
        if success:
            passed += 1
    
    print(f"\nOverall: {passed}/{len(results)} tests passed")
    
    if passed == len(results):
        print("Status: All API tests passed!")
    elif passed > len(results) // 2:
        print("Status: Most API tests passed, some issues to investigate")
    else:
        print("Status: Significant API issues detected")
    
    return results

def check_server_running():
    """檢查服務器是否運行"""
    try:
        response = requests.get('http://127.0.0.1:5000/health', timeout=2)
        return response.status_code == 200
    except:
        return False

if __name__ == '__main__':
    if not check_server_running():
        print("Flask server is not running on port 5000")
        print("Please start the server manually or run the full test with API server startup")
        exit(1)
    
    test_api_endpoints()