<?php
/**
 * CuliUptime PHP Agent Test Runner
 *
 * Runs all test suites for the PHP agent in isolation
 * Provides comprehensive testing without external dependencies
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

class AgentTestRunner
{
    private $totalTests = 0;
    private $totalPassed = 0;
    private $totalFailed = 0;
    private $suiteResults = [];

    public function runAllTestSuites()
    {
        echo "🧪 CuliUptime PHP Agent Test Suite\n";
        echo "===================================\n\n";

        $startTime = microtime(true);

        // Load test classes
        $this->loadTestClasses();

        // Run test suites
        $this->runTestSuite('AgentSecurityTest', 'Security Tests');
        $this->runTestSuite('AgentHMACTest', 'HMAC Authentication Tests');
        $this->runTestSuite('AgentFunctionalTest', 'Functional Tests');
        $this->runTestSuite('AgentValidationTest', 'Validation Tests');
        $this->runTestSuite('AgentNewFeaturesTest', 'New Features Tests');

        $endTime = microtime(true);
        $duration = round($endTime - $startTime, 2);

        // Print overall results
        $this->printOverallResults($duration);

        // Exit with appropriate code
        exit($this->totalFailed > 0 ? 1 : 0);
    }

    private function loadTestClasses()
    {
        $testDir = __DIR__;
        $testFiles = [
            'AgentSecurityTest.php',
            'AgentHMACTest.php',
            'AgentFunctionalTest.php',
            'AgentValidationTest.php',
            'AgentNewFeaturesTest.php'
        ];

        foreach ($testFiles as $file) {
            $filepath = $testDir . '/' . $file;
            if (file_exists($filepath)) {
                require_once $filepath;
            } else {
                echo "❌ ERROR: Test file not found: $file\n";
                exit(1);
            }
        }
    }

    private function runTestSuite($className, $suiteName)
    {
        echo "🔍 Running $suiteName\n";
        echo str_repeat('-', strlen("🔍 Running $suiteName")) . "\n";

        if (!class_exists($className)) {
            echo "❌ ERROR: Test class $className not found\n\n";
            $this->suiteResults[$suiteName] = [
                'status' => 'error',
                'passed' => 0,
                'failed' => 1,
                'total' => 1
            ];
            $this->totalTests++;
            $this->totalFailed++;
            return;
        }

        // Capture output
        ob_start();

        try {
            $testInstance = new $className();
            $testInstance->runAllTests();

            $output = ob_get_clean();
            echo $output;

            // Parse results from output
            $results = $this->parseTestResults($output);
            $this->suiteResults[$suiteName] = $results;

            $this->totalTests += $results['total'];
            $this->totalPassed += $results['passed'];
            $this->totalFailed += $results['failed'];

        } catch (Exception $e) {
            ob_end_clean();
            echo "❌ ERROR running $className: " . $e->getMessage() . "\n";

            $this->suiteResults[$suiteName] = [
                'status' => 'error',
                'passed' => 0,
                'failed' => 1,
                'total' => 1,
                'error' => $e->getMessage()
            ];

            $this->totalTests++;
            $this->totalFailed++;
        }

        echo "\n";
    }

    private function parseTestResults($output)
    {
        $lines = explode("\n", $output);
        $passed = 0;
        $failed = 0;
        $status = 'success';

        foreach ($lines as $line) {
            if (strpos($line, "✓ PASS") === 0) {
                $passed++;
            } elseif (strpos($line, "✗ FAIL") === 0) {
                $failed++;
                $status = 'failed';
            }
        }

        return [
            'status' => $status,
            'passed' => $passed,
            'failed' => $failed,
            'total' => $passed + $failed
        ];
    }

    private function printOverallResults($duration)
    {
        echo "📊 OVERALL TEST RESULTS\n";
        echo "=======================\n\n";

        // Suite breakdown
        foreach ($this->suiteResults as $suiteName => $results) {
            $status = $results['status'] === 'success' ? '✅' :
                     ($results['status'] === 'failed' ? '❌' : '⚠️');

            echo "$status $suiteName: {$results['passed']}/{$results['total']} passed\n";

            if (isset($results['error'])) {
                echo "   Error: {$results['error']}\n";
            }
        }

        echo "\n";

        // Overall statistics
        $successRate = $this->totalTests > 0 ?
            round(($this->totalPassed / $this->totalTests) * 100, 1) : 0;

        echo "📈 STATISTICS\n";
        echo "Total Tests: $this->totalTests\n";
        echo "Passed: $this->totalPassed\n";
        echo "Failed: $this->totalFailed\n";
        echo "Success Rate: $successRate%\n";
        echo "Duration: {$duration}s\n\n";

        // Final verdict
        if ($this->totalFailed === 0) {
            echo "🎉 ALL TESTS PASSED! Agent is ready for deployment.\n";
        } else {
            echo "❌ SOME TESTS FAILED! Review and fix issues before deployment.\n";

            echo "\n🔧 FAILED TEST SUITES:\n";
            foreach ($this->suiteResults as $suiteName => $results) {
                if ($results['status'] !== 'success') {
                    echo "- $suiteName ({$results['failed']} failures)\n";
                }
            }
        }

        echo "\n";
    }

    public function runSingleTest($testClass)
    {
        echo "🧪 Running Single Test: $testClass\n";
        echo "================================\n\n";

        $this->loadTestClasses();

        if (!class_exists($testClass)) {
            echo "❌ ERROR: Test class $testClass not found\n";
            exit(1);
        }

        try {
            $testInstance = new $testClass();
            $testInstance->runAllTests();
        } catch (Exception $e) {
            echo "❌ ERROR running $testClass: " . $e->getMessage() . "\n";
            exit(1);
        }
    }
}

// Main execution
if (basename(__FILE__) === basename($_SERVER['SCRIPT_NAME'])) {
    $runner = new AgentTestRunner();

    // Check command line arguments
    if (isset($argv[1])) {
        $testClass = $argv[1];
        if (strpos($testClass, '.php') !== false) {
            // Testing specific agent file
            echo "🎯 Testing Agent File: $testClass\n";
            echo "============================\n\n";
            $runner->runAllTestSuites();
        } else {
            // Running single test class
            $runner->runSingleTest($testClass);
        }
    } else {
        $runner->runAllTestSuites();
    }
}
?>
