#!/usr/bin/env php
<?php
/**
 * CARE API - SUITE COMPLETA DE TESTES MANUAIS
 * 
 * Este script executa uma bateria completa de testes para validar
 * todas as funcionalidades do plugin Care API.
 * 
 * @package Care_API\Tests
 */

define('CARE_API_TEST_MODE', true);
define('ABSPATH', __DIR__ . '/');

echo "🏥 CARE API - TESTE COMPLETO DE FUNCIONALIDADES\n";
echo "================================================\n\n";

/**
 * Class para executar testes manuais do Care API
 */
class CareAPITestSuite {
    
    private $results = [];
    private $total_tests = 0;
    private $passed_tests = 0;
    private $failed_tests = 0;
    
    public function __construct() {
        echo "🔧 Inicializando suite de testes...\n";
        $this->setup_mock_environment();
    }
    
    /**
     * Setup do ambiente mock para testes
     */
    private function setup_mock_environment() {
        // Mock WordPress functions
        if (!function_exists('plugin_dir_path')) {
            function plugin_dir_path($file) { return dirname($file) . '/'; }
        }
        if (!function_exists('plugin_dir_url')) {
            function plugin_dir_url($file) { return 'http://localhost/wp-content/plugins/' . basename(dirname($file)) . '/'; }
        }
        if (!function_exists('plugin_basename')) {
            function plugin_basename($file) { return basename(dirname($file)) . '/' . basename($file); }
        }
        if (!function_exists('is_plugin_active')) {
            function is_plugin_active($plugin) { return true; } // Mock KiviCare ativo
        }
        if (!function_exists('wp_die')) {
            function wp_die($message, $title = '', $args = []) { die($message); }
        }
        if (!function_exists('esc_html__')) {
            function esc_html__($text, $domain) { return $text; }
        }
        if (!function_exists('get_role')) {
            function get_role($role) { 
                return (object) ['add_cap' => function($cap) {}, 'remove_cap' => function($cap) {}]; 
            }
        }
        if (!function_exists('flush_rewrite_rules')) {
            function flush_rewrite_rules() { return true; }
        }
        if (!function_exists('update_option')) {
            function update_option($name, $value) { return true; }
        }
        if (!function_exists('delete_option')) {
            function delete_option($name) { return true; }
        }
        if (!function_exists('wp_cache_flush')) {
            function wp_cache_flush() { return true; }
        }
        if (!function_exists('current_time')) {
            function current_time($type) { return date($type); }
        }
        if (!function_exists('load_plugin_textdomain')) {
            function load_plugin_textdomain($domain, $deprecated, $plugin_rel_path) { return true; }
        }
        if (!function_exists('plugins_url')) {
            function plugins_url($path, $plugin) { return 'http://localhost/wp-content/plugins' . $path; }
        }
        if (!function_exists('untrailingslashit')) {
            function untrailingslashit($string) { return rtrim($string, '/\\'); }
        }
        if (!function_exists('apply_filters')) {
            function apply_filters($tag, $value) { return $value; }
        }
        if (!function_exists('do_action')) {
            function do_action($tag) { return true; }
        }
        if (!function_exists('add_action')) {
            function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) { return true; }
        }
        if (!function_exists('register_activation_hook')) {
            function register_activation_hook($file, $function) { return true; }
        }
        if (!function_exists('register_deactivation_hook')) {
            function register_deactivation_hook($file, $function) { return true; }
        }
        if (!function_exists('register_uninstall_hook')) {
            function register_uninstall_hook($file, $function) { return true; }
        }
        if (!function_exists('activate_plugin')) {
            function activate_plugin($plugin) { return true; }
        }
        if (!defined('WP_DEBUG')) {
            define('WP_DEBUG', true);
        }
        if (!defined('CARE_API_VERSION')) {
            define('CARE_API_VERSION', '1.0.0');
        }
        
        echo "✅ Ambiente mock configurado\n\n";
    }
    
    /**
     * Executa todos os testes
     */
    public function run_all_tests() {
        echo "🚀 INICIANDO TESTES COMPLETOS\n";
        echo "==============================\n\n";
        
        // 1. TESTES DE INSTALAÇÃO
        $this->test_installation();
        
        // 2. TESTES DE ESTRUTURA DE ARQUIVOS
        $this->test_file_structure();
        
        // 3. TESTES DE SINTAXE PHP
        $this->test_php_syntax();
        
        // 4. TESTES DE CLASSES PRINCIPAIS
        $this->test_main_classes();
        
        // 5. TESTES DE CONSTANTES E CONFIGURAÇÕES
        $this->test_constants_and_config();
        
        // 6. TESTES DE ENDPOINTS (estrutura)
        $this->test_endpoint_structure();
        
        // 7. TESTES DE MODELOS
        $this->test_models();
        
        // 8. TESTES DE SERVIÇOS
        $this->test_services();
        
        // 9. TESTES DE MIDDLEWARE
        $this->test_middleware();
        
        // 10. TESTES DE UTILITÁRIOS
        $this->test_utilities();
        
        // Relatório final
        $this->generate_report();
    }
    
    /**
     * Teste de instalação do plugin
     */
    private function test_installation() {
        echo "📦 1. TESTES DE INSTALAÇÃO\n";
        echo "==========================\n";
        
        // Teste 1.1: Arquivo principal existe
        $this->run_test('Plugin principal existe', function() {
            return file_exists(__DIR__ . '/src/care-api.php');
        });
        
        // Teste 1.2: Cabeçalho do plugin válido
        $this->run_test('Cabeçalho do plugin válido', function() {
            $content = file_get_contents(__DIR__ . '/src/care-api.php');
            return strpos($content, 'Plugin Name: Care API') !== false &&
                   strpos($content, 'Version: 1.0.0') !== false;
        });
        
        // Teste 1.3: Classe principal pode ser instanciada
        $this->run_test('Classe principal carrega', function() {
            try {
                $content = file_get_contents(__DIR__ . '/src/care-api.php');
                // Verificar se a classe Care_API está definida no arquivo
                return strpos($content, 'class Care_API') !== false &&
                       strpos($content, 'public static function instance()') !== false;
            } catch (Exception $e) {
                return false;
            }
        });
        
        echo "\n";
    }
    
    /**
     * Teste de estrutura de arquivos
     */
    private function test_file_structure() {
        echo "📁 2. TESTES DE ESTRUTURA DE ARQUIVOS\n";
        echo "=====================================\n";
        
        $required_files = [
            '/src/care-api.php' => 'Arquivo principal',
            '/src/includes/class-api-init.php' => 'Inicializador API',
            '/src/includes/endpoints' => 'Diretório endpoints',
            '/src/includes/models' => 'Diretório models',
            '/src/includes/services' => 'Diretório services',
            '/src/includes/middleware' => 'Diretório middleware',
            '/src/includes/utils' => 'Diretório utilitários',
            '/src/admin' => 'Diretório admin',
            '/tests' => 'Diretório testes',
            '/composer.json' => 'Composer config',
            '/phpunit.xml' => 'PHPUnit config',
        ];
        
        foreach ($required_files as $file => $description) {
            $this->run_test($description, function() use ($file) {
                return file_exists(__DIR__ . $file);
            });
        }
        
        echo "\n";
    }
    
    /**
     * Teste de sintaxe PHP
     */
    private function test_php_syntax() {
        echo "🔍 3. TESTES DE SINTAXE PHP\n";
        echo "===========================\n";
        
        $php_files = [];
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator(__DIR__ . '/src')
        );
        
        foreach ($iterator as $file) {
            if ($file->getExtension() === 'php') {
                $php_files[] = $file->getPathname();
            }
        }
        
        $syntax_errors = 0;
        foreach ($php_files as $file) {
            $relative_path = str_replace(__DIR__ . '/', '', $file);
            
            $this->run_test("Sintaxe: $relative_path", function() use ($file, &$syntax_errors) {
                $output = shell_exec("php -l '$file' 2>&1");
                $has_syntax_error = strpos($output, 'Parse error') !== false || 
                                   strpos($output, 'Fatal error') !== false;
                if ($has_syntax_error) {
                    $syntax_errors++;
                }
                return !$has_syntax_error;
            });
        }
        
        echo "\n";
    }
    
    /**
     * Teste das classes principais
     */
    private function test_main_classes() {
        echo "🏗️  4. TESTES DE CLASSES PRINCIPAIS\n";
        echo "===================================\n";
        
        // Mock classes if they don't exist to avoid fatal errors
        if (!class_exists('Care_API_Init')) {
            eval('class Care_API_Init { public static function instance() { return new self(); } }');
        }
        
        $main_classes = [
            'Care_API' => '/src/care-api.php',
            'Care_API_Init' => '/src/includes/class-api-init.php',
        ];
        
        foreach ($main_classes as $class => $file) {
            $this->run_test("Classe $class existe", function() use ($class, $file) {
                if (file_exists(__DIR__ . $file)) {
                    try {
                        $content = file_get_contents(__DIR__ . $file);
                        return strpos($content, "class $class") !== false;
                    } catch (Exception $e) {
                        return false;
                    }
                }
                return false;
            });
        }
        
        echo "\n";
    }
    
    /**
     * Teste de constantes e configurações
     */
    private function test_constants_and_config() {
        echo "⚙️  5. TESTES DE CONSTANTES E CONFIGURAÇÕES\n";
        echo "===========================================\n";
        
        $this->run_test('Constante CARE_API_VERSION definida', function() {
            return defined('CARE_API_VERSION');
        });
        
        $this->run_test('Composer.json válido', function() {
            $composer = json_decode(file_get_contents(__DIR__ . '/composer.json'), true);
            return isset($composer['name']) && isset($composer['require']);
        });
        
        $this->run_test('PHPUnit.xml configurado', function() {
            return file_exists(__DIR__ . '/phpunit.xml') && 
                   strpos(file_get_contents(__DIR__ . '/phpunit.xml'), 'KiviCare API') !== false;
        });
        
        echo "\n";
    }
    
    /**
     * Teste de estrutura dos endpoints
     */
    private function test_endpoint_structure() {
        echo "🌐 6. TESTES DE ESTRUTURA DOS ENDPOINTS\n";
        echo "=======================================\n";
        
        $endpoint_files = [
            'class-auth-endpoints.php' => 'Endpoint Auth',
            'class-clinic-endpoints.php' => 'Endpoint Clinics', 
            'class-patient-endpoints.php' => 'Endpoint Patients',
            'class-doctor-endpoints.php' => 'Endpoint Doctors',
            'class-appointment-endpoints.php' => 'Endpoint Appointments',
            'class-encounter-endpoints.php' => 'Endpoint Encounters',
            'class-prescription-endpoints.php' => 'Endpoint Prescriptions',
            'class-bill-endpoints.php' => 'Endpoint Bills',
        ];
        
        foreach ($endpoint_files as $file => $description) {
            $this->run_test($description . ' existe', function() use ($file) {
                return file_exists(__DIR__ . '/src/includes/endpoints/' . $file);
            });
        }
        
        echo "\n";
    }
    
    /**
     * Teste dos modelos
     */
    private function test_models() {
        echo "📊 7. TESTES DE MODELOS\n";
        echo "=======================\n";
        
        $model_files = [
            'class-clinic.php' => 'Model Clinic',
            'class-patient.php' => 'Model Patient', 
            'class-doctor.php' => 'Model Doctor',
            'class-appointment.php' => 'Model Appointment',
            'class-encounter.php' => 'Model Encounter',
            'class-prescription.php' => 'Model Prescription',
            'class-bill.php' => 'Model Bill',
            'class-service.php' => 'Model Service',
        ];
        
        foreach ($model_files as $file => $description) {
            $this->run_test($description . ' existe', function() use ($file) {
                return file_exists(__DIR__ . '/src/includes/models/' . $file);
            });
        }
        
        echo "\n";
    }
    
    /**
     * Teste dos serviços
     */
    private function test_services() {
        echo "🔧 8. TESTES DE SERVIÇOS\n";
        echo "========================\n";
        
        $service_files = [
            'class-auth-service.php' => 'Service Auth',
            'class-jwt-service.php' => 'Service JWT',
            'class-cache-service.php' => 'Service Cache',
            'class-integration-service.php' => 'Service Integration',
            'class-clinic-isolation-service.php' => 'Service Clinic Isolation',
            'class-permission-service.php' => 'Service Permission',
            'class-session-service.php' => 'Service Session',
            'class-response-standardization-service.php' => 'Service Response',
            'class-performance-monitoring-service.php' => 'Service Performance',
        ];
        
        foreach ($service_files as $file => $description) {
            $this->run_test($description . ' existe', function() use ($file) {
                return file_exists(__DIR__ . '/src/includes/services/' . $file);
            });
        }
        
        // Testar serviços de database
        $database_services = [
            'class-clinic-service.php' => 'Database Service Clinic',
            'class-patient-service.php' => 'Database Service Patient',
            'class-doctor-service.php' => 'Database Service Doctor',
            'class-appointment-service.php' => 'Database Service Appointment',
            'class-encounter-service.php' => 'Database Service Encounter',
            'class-prescription-service.php' => 'Database Service Prescription',
            'class-bill-service.php' => 'Database Service Bill',
        ];
        
        foreach ($database_services as $file => $description) {
            $this->run_test($description . ' existe', function() use ($file) {
                return file_exists(__DIR__ . '/src/includes/services/database/' . $file);
            });
        }
        
        echo "\n";
    }
    
    /**
     * Teste do middleware
     */
    private function test_middleware() {
        echo "🛡️  9. TESTES DE MIDDLEWARE\n";
        echo "===========================\n";
        
        $this->run_test('JWT Middleware existe', function() {
            return file_exists(__DIR__ . '/src/includes/middleware/class-jwt-middleware.php');
        });
        
        echo "\n";
    }
    
    /**
     * Teste dos utilitários
     */
    private function test_utilities() {
        echo "🛠️  10. TESTES DE UTILITÁRIOS\n";
        echo "=============================\n";
        
        $util_files = [
            'class-api-logger.php' => 'Utility Logger',
            'class-error-handler.php' => 'Utility Error Handler',
            'class-input-validator.php' => 'Utility Input Validator',
        ];
        
        foreach ($util_files as $file => $description) {
            $this->run_test($description . ' existe', function() use ($file) {
                return file_exists(__DIR__ . '/src/includes/utils/' . $file);
            });
        }
        
        echo "\n";
    }
    
    /**
     * Executa um teste individual
     */
    private function run_test($name, $callback) {
        $this->total_tests++;
        
        try {
            $result = $callback();
            if ($result) {
                echo "✅ $name\n";
                $this->passed_tests++;
                $this->results[] = ['name' => $name, 'status' => 'PASS'];
            } else {
                echo "❌ $name\n";
                $this->failed_tests++;
                $this->results[] = ['name' => $name, 'status' => 'FAIL'];
            }
        } catch (Exception $e) {
            echo "💥 $name - ERROR: " . $e->getMessage() . "\n";
            $this->failed_tests++;
            $this->results[] = ['name' => $name, 'status' => 'ERROR', 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Gera relatório final
     */
    private function generate_report() {
        echo "\n🎯 RELATÓRIO FINAL DOS TESTES\n";
        echo "=============================\n\n";
        
        echo "📊 ESTATÍSTICAS:\n";
        echo "  Total de testes: {$this->total_tests}\n";
        echo "  Testes aprovados: {$this->passed_tests}\n";
        echo "  Testes reprovados: {$this->failed_tests}\n";
        
        $success_rate = round(($this->passed_tests / $this->total_tests) * 100, 2);
        echo "  Taxa de sucesso: {$success_rate}%\n\n";
        
        if ($success_rate >= 90) {
            echo "🎉 EXCELENTE! Plugin está bem estruturado.\n";
        } elseif ($success_rate >= 70) {
            echo "👍 BOM! Algumas melhorias necessárias.\n"; 
        } elseif ($success_rate >= 50) {
            echo "⚠️  REGULAR! Muitas melhorias necessárias.\n";
        } else {
            echo "🚨 CRÍTICO! Plugin precisa de refatoração significativa.\n";
        }
        
        echo "\n📋 RESUMO DOS PROBLEMAS ENCONTRADOS:\n";
        $failed_count = 0;
        foreach ($this->results as $result) {
            if ($result['status'] !== 'PASS') {
                $failed_count++;
                $status = $result['status'] === 'FAIL' ? '❌' : '💥';
                echo "  $status {$result['name']}\n";
                if (isset($result['error'])) {
                    echo "     → {$result['error']}\n";
                }
            }
        }
        
        if ($failed_count === 0) {
            echo "  ✨ Nenhum problema encontrado!\n";
        }
        
        echo "\n🔧 PRÓXIMOS PASSOS RECOMENDADOS:\n";
        echo "  1. Corrigir problemas de sintaxe PHP\n";
        echo "  2. Instalar dependências Composer\n";
        echo "  3. Configurar ambiente de testes WordPress\n";
        echo "  4. Executar testes PHPUnit\n";
        echo "  5. Testar em ambiente WordPress real\n";
        
        echo "\n📅 Teste executado em: " . date('Y-m-d H:i:s') . "\n";
        echo "🏥 Care API Test Suite - Descomplicar® Crescimento Digital\n";
    }
}

// Executar testes
$test_suite = new CareAPITestSuite();
$test_suite->run_all_tests();