<?php
/**
 * WordPress API Endpoints Registration Test
 *
 * This script tests if all Care API endpoints are properly registered 
 * with WordPress REST API system.
 *
 * @package Care_API
 * @version 1.0.0
 */

// Set up WordPress environment
define('WP_USE_THEMES', false);

// Try to find WordPress installation
$wp_paths = [
    '/var/www/html/wp-load.php',
    '/usr/src/wordpress/wp-load.php', 
    dirname(dirname(dirname(__FILE__))) . '/wp-load.php',
    '/home/wordpress/wp-load.php'
];

$wp_loaded = false;
foreach ($wp_paths as $path) {
    if (file_exists($path)) {
        require_once($path);
        $wp_loaded = true;
        break;
    }
}

if (!$wp_loaded) {
    echo "⚠️ WordPress não encontrado. Executando teste offline...\n\n";
}

echo "🏥 CARE API - TESTE DE ENDPOINTS REST\n";
echo "=====================================\n\n";

echo "🔧 Configurando teste de endpoints...\n";

// Load Care API files (commented out as we test structure only)
// require_once __DIR__ . '/src/care-api.php';

echo "✅ Care API carregado\n\n";

echo "🚀 TESTANDO ENDPOINTS REST API\n";
echo "===============================\n\n";

// Test 1: Check if namespaces are consistent
echo "1. 🌐 TESTANDO CONSISTÊNCIA DOS NAMESPACES\n";
echo "==========================================\n";

$endpoint_files = [
    'class-auth-endpoints.php' => 'Care_API\\Endpoints\\Auth_Endpoints',
    'class-clinic-endpoints.php' => 'Care_API\\Endpoints\\Clinic_Endpoints',
    'class-patient-endpoints.php' => 'Care_API\\Endpoints\\Patient_Endpoints',
    'class-appointment-endpoints.php' => 'Care_API\\Endpoints\\Appointment_Endpoints',
    'class-doctor-endpoints.php' => 'Care_API\\Endpoints\\Doctor_Endpoints',
    'class-encounter-endpoints.php' => 'Care_API\\Endpoints\\Encounter_Endpoints',
    'class-prescription-endpoints.php' => 'Care_API\\Endpoints\\Prescription_Endpoints',
    'class-bill-endpoints.php' => 'Care_API\\Endpoints\\Bill_Endpoints'
];

$namespace_consistent = true;
foreach ($endpoint_files as $file => $class) {
    $filepath = __DIR__ . '/src/includes/endpoints/' . $file;
    if (file_exists($filepath)) {
        $content = file_get_contents($filepath);
        
        // Check for hardcoded namespaces
        if (strpos($content, "'kivicare/v1'") !== false) {
            echo "❌ $file contém namespace inconsistente 'kivicare/v1'\n";
            $namespace_consistent = false;
        } elseif (strpos($content, "'care/v1'") !== false || strpos($content, "self::NAMESPACE") !== false || strpos($content, "self::API_NAMESPACE") !== false) {
            echo "✅ $file usa namespace correto\n";
        } else {
            echo "⚠️ $file sem namespace detectado\n";
        }
    } else {
        echo "❌ $file não encontrado\n";
        $namespace_consistent = false;
    }
}

echo "\n📊 Resultado dos namespaces: " . ($namespace_consistent ? "✅ CONSISTENTE" : "❌ INCONSISTENTE") . "\n\n";

// Test 2: Check class structure
echo "2. 🏗️ TESTANDO ESTRUTURA DAS CLASSES\n";
echo "=====================================\n";

$classes_working = 0;
$total_classes = count($endpoint_files);

foreach ($endpoint_files as $file => $class) {
    $filepath = __DIR__ . '/src/includes/endpoints/' . $file;
    if (file_exists($filepath)) {
        require_once $filepath;
        if (class_exists($class)) {
            if (method_exists($class, 'register_routes')) {
                echo "✅ $class - estrutura OK\n";
                $classes_working++;
            } else {
                echo "❌ $class - método register_routes não encontrado\n";
            }
        } else {
            echo "❌ $class - classe não existe\n";
        }
    }
}

echo "\n📊 Classes funcionando: $classes_working/$total_classes\n\n";

// Test 3: API Structure validation
echo "3. 🎯 VALIDAÇÃO DA ESTRUTURA DA API\n";
echo "===================================\n";

$api_structure_score = 0;
$max_structure_score = 8;

// Check core API files
$core_files = [
    'src/care-api.php' => 'Plugin principal',
    'src/includes/class-api-init.php' => 'Inicializador da API',
    'src/includes/services/class-auth-service.php' => 'Serviço de autenticação',
    'src/includes/services/class-permission-service.php' => 'Serviço de permissões',
    'src/includes/services/class-session-service.php' => 'Gerenciador de sessões',
    'src/includes/middleware/class-jwt-middleware.php' => 'Middleware JWT',
    'src/includes/utils/class-input-validator.php' => 'Validador de entrada',
    'src/includes/utils/class-error-handler.php' => 'Manipulador de erros'
];

foreach ($core_files as $file => $description) {
    if (file_exists(__DIR__ . '/' . $file)) {
        echo "✅ $description\n";
        $api_structure_score++;
    } else {
        echo "❌ $description - arquivo não encontrado\n";
    }
}

echo "\n📊 Estrutura da API: $api_structure_score/$max_structure_score (" . 
     round(($api_structure_score/$max_structure_score) * 100, 1) . "%)\n\n";

// Test 4: Endpoint Coverage
echo "4. 📋 COBERTURA DE ENDPOINTS\n";
echo "============================\n";

$expected_endpoints = [
    'Authentication' => ['login', 'logout', 'refresh', 'profile'],
    'Clinics' => ['get_clinics', 'create_clinic', 'get_clinic', 'update_clinic', 'delete_clinic'],
    'Patients' => ['get_patient', 'create_patient', 'update_patient', 'search_patients'],
    'Appointments' => ['get_appointments', 'create_appointment', 'update_appointment', 'cancel_appointment'],
    'Encounters' => ['get_encounters', 'create_encounter', 'update_encounter'],
    'Prescriptions' => ['get_prescriptions', 'create_prescription', 'update_prescription'],
    'Bills' => ['get_bills', 'create_bill', 'update_bill'],
    'Doctors' => ['get_doctors', 'create_doctor', 'get_doctor', 'update_doctor']
];

$total_endpoints = 0;
$implemented_endpoints = 0;

foreach ($expected_endpoints as $category => $methods) {
    echo "\n📁 $category:\n";
    $category_file = strtolower(str_replace(['s'], '', $category));
    if ($category === 'Authentication') {
        $filepath = __DIR__ . '/src/includes/endpoints/class-auth-endpoints.php';
    } else {
        $filepath = __DIR__ . '/src/includes/endpoints/class-' . $category_file . '-endpoints.php';
    }
    
    if (file_exists($filepath)) {
        $content = file_get_contents($filepath);
        
        foreach ($methods as $method) {
            $total_endpoints++;
            if (strpos($content, "function $method") !== false || strpos($content, "$method(") !== false) {
                echo "  ✅ $method\n";
                $implemented_endpoints++;
            } else {
                echo "  ❌ $method\n";
            }
        }
    } else {
        foreach ($methods as $method) {
            $total_endpoints++;
            echo "  ❌ $method (arquivo não existe)\n";
        }
    }
}

$coverage_percentage = round(($implemented_endpoints / $total_endpoints) * 100, 1);
echo "\n📊 Cobertura de endpoints: $implemented_endpoints/$total_endpoints ($coverage_percentage%)\n\n";

// Final Summary
echo "🎯 RELATÓRIO FINAL\n";
echo "==================\n\n";

$overall_score = (
    ($namespace_consistent ? 25 : 0) +
    (($classes_working / $total_classes) * 25) +
    (($api_structure_score / $max_structure_score) * 25) +
    (($implemented_endpoints / $total_endpoints) * 25)
);

echo "📊 PONTUAÇÃO GERAL: " . round($overall_score, 1) . "/100\n";

if ($overall_score >= 90) {
    echo "🏆 EXCELENTE! API pronta para produção\n";
} elseif ($overall_score >= 80) {
    echo "✅ MUITO BOM! API pronta para TDD GREEN phase\n";
} elseif ($overall_score >= 70) {
    echo "👍 BOM! Pequenos ajustes necessários\n";
} elseif ($overall_score >= 60) {
    echo "⚠️ REGULAR! Melhorias necessárias\n";
} else {
    echo "❌ RUIM! Requer refatoração significativa\n";
}

echo "\n🔧 STATUS DOS COMPONENTES:\n";
echo "  🌐 Namespaces: " . ($namespace_consistent ? "✅" : "❌") . "\n";
echo "  🏗️ Classes: " . round(($classes_working / $total_classes) * 100, 1) . "% (" . ($classes_working >= $total_classes * 0.8 ? "✅" : "❌") . ")\n";
echo "  🎯 Estrutura: " . round(($api_structure_score / $max_structure_score) * 100, 1) . "% (" . ($api_structure_score >= $max_structure_score * 0.8 ? "✅" : "❌") . ")\n";
echo "  📋 Endpoints: " . $coverage_percentage . "% (" . ($coverage_percentage >= 80 ? "✅" : "❌") . ")\n";

echo "\n🚀 PRÓXIMOS PASSOS:\n";
if ($overall_score >= 80) {
    echo "  1. ✅ Executar testes TDD (CONTRACT TESTS)\n";
    echo "  2. 🌍 Testar em ambiente WordPress\n";
    echo "  3. 📱 Validar com cliente REST (Postman/Insomnia)\n";
    echo "  4. 📝 Documentar API (OpenAPI/Swagger)\n";
} else {
    echo "  1. 🔧 Corrigir issues de estrutura\n";
    echo "  2. 🛠️ Implementar endpoints em falta\n";
    echo "  3. 🧪 Executar testes unitários\n";
    echo "  4. 🔄 Re-executar este teste\n";
}

echo "\n📅 Teste executado em: " . date('Y-m-d H:i:s') . "\n";
echo "🏥 Care API Endpoints Test Suite - Descomplicar®\n";