"""
Simple test to verify recovery API endpoints are accessible
"""

import requests
import sys
import os

# Add the backend directory to the path
sys.path.insert(0, os.path.dirname(__file__))

def test_recovery_endpoints():
    """Test that recovery endpoints are accessible"""
    base_url = "http://localhost:8000"
    
    # Test endpoints without authentication (should return 401)
    endpoints = [
        "/api/admin/deleted-shots/",
        "/api/admin/deleted-assets/",
        "/api/admin/recovery-stats/"
    ]
    
    print("Testing Recovery Management API Endpoints...")
    print("=" * 50)
    
    all_passed = True
    
    for endpoint in endpoints:
        try:
            response = requests.get(f"{base_url}{endpoint}", timeout=5)
            
            # We expect 401 (unauthorized) or 200 (if somehow authenticated)
            # 404 would indicate the endpoint doesn't exist
            expected_statuses = [200, 401, 422]  # 422 for validation errors
            
            if response.status_code in expected_statuses:
                print(f"✅ {endpoint}: {response.status_code} (endpoint exists)")
            else:
                print(f"❌ {endpoint}: {response.status_code} (unexpected status)")
                all_passed = False
                
        except requests.exceptions.ConnectionError:
            print(f"⚠️  {endpoint}: Connection failed (server not running?)")
            all_passed = False
        except Exception as e:
            print(f"❌ {endpoint}: Error - {e}")
            all_passed = False
    
    print("=" * 50)
    
    # Test POST endpoints (should return 401 or 422)
    post_endpoints = [
        "/api/admin/shots/1/recover",
        "/api/admin/assets/1/recover",
        "/api/admin/shots/bulk-recover",
        "/api/admin/assets/bulk-recover"
    ]
    
    print("Testing POST endpoints...")
    
    for endpoint in post_endpoints:
        try:
            if "bulk-recover" in endpoint:
                # Send empty payload for bulk endpoints
                response = requests.post(f"{base_url}{endpoint}", 
                                       json={"shot_ids": []} if "shots" in endpoint else {"asset_ids": []},
                                       timeout=5)
            else:
                response = requests.post(f"{base_url}{endpoint}", timeout=5)
            
            expected_statuses = [200, 400, 401, 404, 422]
            
            if response.status_code in expected_statuses:
                print(f"✅ {endpoint}: {response.status_code} (endpoint exists)")
            else:
                print(f"❌ {endpoint}: {response.status_code} (unexpected status)")
                all_passed = False
                
        except requests.exceptions.ConnectionError:
            print(f"⚠️  {endpoint}: Connection failed (server not running?)")
            all_passed = False
        except Exception as e:
            print(f"❌ {endpoint}: Error - {e}")
            all_passed = False
    
    print("=" * 50)
    
    if all_passed:
        print("🎉 All recovery API endpoints are accessible!")
        print("✅ Requirement 4.2: API endpoints continue to work - PASSED")
    else:
        print("⚠️  Some endpoints had issues. Check server status.")
        print("❌ Requirement 4.2: API endpoints continue to work - NEEDS REVIEW")
    
    return all_passed

def test_frontend_files():
    """Test that frontend files exist"""
    print("\nTesting Frontend File Structure...")
    print("=" * 50)
    
    files_to_check = [
        "../frontend/src/services/recovery.ts",
        "../frontend/src/views/admin/DeletedItemsManagementView.vue",
        "../frontend/src/components/layout/AppSidebar.vue",
        "../frontend/src/router/index.ts"
    ]
    
    all_exist = True
    
    for file_path in files_to_check:
        if os.path.exists(file_path):
            print(f"✅ {file_path}: exists")
        else:
            print(f"❌ {file_path}: missing")
            all_exist = False
    
    print("=" * 50)
    
    if all_exist:
        print("🎉 All required frontend files exist!")
        print("✅ Requirement 4.1: Component interfaces remain unchanged - PASSED")
    else:
        print("⚠️  Some frontend files are missing.")
        print("❌ Requirement 4.1: Component interfaces remain unchanged - NEEDS REVIEW")
    
    return all_exist

def test_route_configuration():
    """Test that route configuration is preserved"""
    print("\nTesting Route Configuration...")
    print("=" * 50)
    
    router_file = "../frontend/src/router/index.ts"
    
    if not os.path.exists(router_file):
        print(f"❌ Router file not found: {router_file}")
        return False
    
    with open(router_file, 'r') as f:
        content = f.read()
    
    required_elements = [
        "/admin/deleted-items",
        "RecoveryManagement",
        "DeletedItemsManagementView"
    ]
    
    all_found = True
    
    for element in required_elements:
        if element in content:
            print(f"✅ Route element found: {element}")
        else:
            print(f"❌ Route element missing: {element}")
            all_found = False
    
    print("=" * 50)
    
    if all_found:
        print("🎉 Route configuration is preserved!")
        print("✅ Requirement 4.3: Navigation and routing functionality is preserved - PASSED")
    else:
        print("⚠️  Route configuration has issues.")
        print("❌ Requirement 4.3: Navigation and routing functionality is preserved - NEEDS REVIEW")
    
    return all_found

if __name__ == "__main__":
    print("Recovery Management Functionality Preservation Test")
    print("=" * 60)
    print("Testing Requirements 4.1, 4.2, 4.3, 4.4, 4.5")
    print("=" * 60)
    
    # Run tests
    api_test = test_recovery_endpoints()
    frontend_test = test_frontend_files()
    route_test = test_route_configuration()
    
    print("\n" + "=" * 60)
    print("FINAL RESULTS:")
    print("=" * 60)
    
    if api_test and frontend_test and route_test:
        print("🎉 ALL TESTS PASSED!")
        print("✅ Existing functionality is preserved after terminology changes")
    else:
        print("⚠️  SOME TESTS FAILED!")
        print("❌ Review the issues above before proceeding")
    
    print("=" * 60)