<?php
/**
 * Smart Reflow Engine Parity Test
 * 
 * Tests that PHP and JavaScript implementations produce identical results.
 * Run this from WordPress admin or CLI to verify cross-platform parity.
 * 
 * @package CastConductor
 * @since 5.2.1
 */

// For CLI execution
if (!defined('ABSPATH')) {
    // Try to load WordPress
    $wp_load_paths = [
        __DIR__ . '/../../../../wp-load.php',
        __DIR__ . '/../../../../../wp-load.php',
    ];
    foreach ($wp_load_paths as $path) {
        if (file_exists($path)) {
            require_once $path;
            break;
        }
    }
}

// Ensure the reflow engine is loaded
require_once __DIR__ . '/../includes/class-castconductor-reflow-engine.php';

/**
 * Test cases for reflow parity verification
 */
class CastConductor_Reflow_Parity_Test {

    private $test_results = [];

    /**
     * Run all parity tests
     */
    public function run_all_tests() {
        echo "=== Smart Reflow Engine Parity Tests ===\n\n";

        $this->test_needs_reflow();
        $this->test_layout_mode_detection();
        $this->test_proportional_scale();
        $this->test_vertical_stack();
        $this->test_horizontal_spread();
        $this->test_real_world_scenarios();

        $this->print_summary();
    }

    /**
     * Test needsReflow function
     */
    private function test_needs_reflow() {
        echo "Testing: needsReflow()\n";

        $test_cases = [
            // [authoredW, authoredH, targetW, targetH, expected]
            [1280, 240, 1280, 240, false, 'Same size - no reflow'],
            [1280, 240, 640, 360, true, 'Different aspect ratio - needs reflow'],
            [1280, 240, 1280, 245, false, 'Within tolerance (2%) - no reflow'],
            [1280, 720, 640, 360, false, 'Same aspect ratio - no reflow'],
            [800, 600, 400, 300, false, 'Proportionally scaled - no reflow'],
        ];

        foreach ($test_cases as $case) {
            list($aw, $ah, $tw, $th, $expected, $description) = $case;
            $result = CastConductor_Reflow_Engine::needs_reflow($aw, $ah, $tw, $th);
            $passed = ($result === $expected);
            $this->record_result('needsReflow', $description, $passed, $expected, $result);
        }

        echo "\n";
    }

    /**
     * Test layout mode detection
     */
    private function test_layout_mode_detection() {
        echo "Testing: getReflowLayoutMode()\n";

        $test_cases = [
            // [authoredW, authoredH, targetW, targetH, expected]
            [1280, 240, 640, 360, 'vertical-stack', 'Lower Third → Left Half'],
            [640, 360, 1280, 240, 'horizontal-spread', 'Left Half → Lower Third'],
            [800, 600, 640, 480, 'proportional', 'Similar aspect ratios'],
            [1280, 720, 640, 360, 'proportional', '16:9 to 16:9'],
        ];

        foreach ($test_cases as $case) {
            list($aw, $ah, $tw, $th, $expected, $description) = $case;
            $result = CastConductor_Reflow_Engine::get_reflow_layout_mode($aw, $ah, $tw, $th);
            $passed = ($result === $expected);
            $this->record_result('getReflowLayoutMode', $description, $passed, $expected, $result);
        }

        echo "\n";
    }

    /**
     * Test proportional scale calculations
     */
    private function test_proportional_scale() {
        echo "Testing: Proportional Scale Layout\n";

        // Test case: 1280x720 → 640x360 (same aspect ratio)
        $layers = [
            [
                'id' => 'layer-1',
                'kind' => 'token-image',
                'x' => 16,
                'y' => 16,
                'width' => 200,
                'height' => 200,
            ],
            [
                'id' => 'layer-2',
                'kind' => 'token-text',
                'x' => 240,
                'y' => 50,
                'width' => 400,
                'height' => 60,
                'style' => ['font_size' => 36],
            ],
        ];

        $result = CastConductor_Reflow_Engine::calculate_reflow_layout($layers, 1280, 720, 640, 360);

        // Expected scale factor: 0.5
        $passed = isset($result[0]['_reflow']);
        $this->record_result('proportionalScale', 'Adds _reflow property', $passed, true, $passed);

        if ($passed) {
            // Check proportional coordinates
            $img_x = $result[0]['_reflow']['x'];
            $expected_x = 8; // 16 * 0.5
            $passed = (abs($img_x - $expected_x) < 2);
            $this->record_result('proportionalScale', 'Image X scaled', $passed, $expected_x, $img_x);

            $text_w = $result[1]['_reflow']['width'];
            $expected_w = 200; // 400 * 0.5
            $passed = (abs($text_w - $expected_w) < 10);
            $this->record_result('proportionalScale', 'Text width scaled', $passed, $expected_w, $text_w);
        }

        echo "\n";
    }

    /**
     * Test vertical stack layout (wide → tall)
     */
    private function test_vertical_stack() {
        echo "Testing: Vertical Stack Layout (wide → tall)\n";

        // Test case: 1280x240 → 640x360 (Lower Third → Left Half)
        $layers = [
            [
                'id' => 'artwork',
                'kind' => 'token-image',
                'x' => 16,
                'y' => 20,
                'width' => 200,
                'height' => 200,
            ],
            [
                'id' => 'title',
                'kind' => 'token-text',
                'x' => 232,
                'y' => 40,
                'width' => 500,
                'height' => 50,
                'style' => ['font_size' => 32],
            ],
            [
                'id' => 'artist',
                'kind' => 'token-text',
                'x' => 232,
                'y' => 110,
                'width' => 500,
                'height' => 40,
                'style' => ['font_size' => 24],
            ],
        ];

        $result = CastConductor_Reflow_Engine::calculate_reflow_layout($layers, 1280, 240, 640, 360);

        // In vertical stack mode, content should reorganize top-to-bottom
        $passed = isset($result[0]['_reflow']);
        $this->record_result('verticalStack', 'Has reflow data', $passed, true, $passed);

        if ($passed) {
            // Artwork should be at top-center-ish
            $art_y = $result[0]['_reflow']['y'];
            $this->record_result('verticalStack', 'Artwork Y position', true, '~16', $art_y);

            // Text should be below artwork
            $text_y = $result[1]['_reflow']['y'];
            $art_bottom = $art_y + $result[0]['_reflow']['height'];
            $passed = ($text_y >= $art_bottom);
            $this->record_result('verticalStack', 'Text below artwork', $passed, ">=$art_bottom", $text_y);
        }

        echo "\n";
    }

    /**
     * Test horizontal spread layout (tall → wide)
     */
    private function test_horizontal_spread() {
        echo "Testing: Horizontal Spread Layout (tall → wide)\n";

        // Test case: 640x360 → 1280x240 (Left Half → Lower Third)
        $layers = [
            [
                'id' => 'artwork',
                'kind' => 'token-image',
                'x' => 16,
                'y' => 16,
                'width' => 200,
                'height' => 200,
            ],
            [
                'id' => 'title',
                'kind' => 'token-text',
                'x' => 16,
                'y' => 236,
                'width' => 400,
                'height' => 50,
                'style' => ['font_size' => 28],
            ],
        ];

        $result = CastConductor_Reflow_Engine::calculate_reflow_layout($layers, 640, 360, 1280, 240);

        // In horizontal spread mode, content should reorganize left-to-right
        $passed = isset($result[0]['_reflow']);
        $this->record_result('horizontalSpread', 'Has reflow data', $passed, true, $passed);

        if ($passed) {
            // Artwork should stay on left
            $art_x = $result[0]['_reflow']['x'];
            $this->record_result('horizontalSpread', 'Artwork X position', true, '~16', $art_x);

            // Text should be to the right of artwork
            $text_x = $result[1]['_reflow']['x'];
            $art_right = $art_x + $result[0]['_reflow']['width'];
            $passed = ($text_x >= $art_right);
            $this->record_result('horizontalSpread', 'Text right of artwork', $passed, ">=$art_right", $text_x);
        }

        echo "\n";
    }

    /**
     * Test real-world scenarios
     */
    private function test_real_world_scenarios() {
        echo "Testing: Real-World Scenarios\n";

        // Scenario 1: Now Playing block from Lower Third → Full Screen
        $now_playing = [
            [
                'id' => 'artwork',
                'kind' => 'token-image',
                'x' => 16,
                'y' => 20,
                'width' => 200,
                'height' => 200,
            ],
            [
                'id' => 'song-title',
                'kind' => 'token-text',
                'x' => 232,
                'y' => 50,
                'width' => 800,
                'height' => 60,
                'style' => ['font_size' => 36],
            ],
            [
                'id' => 'artist',
                'kind' => 'token-text',
                'x' => 232,
                'y' => 130,
                'width' => 800,
                'height' => 50,
                'style' => ['font_size' => 28],
            ],
        ];

        // Lower Third → Full Screen (major aspect change)
        $result = CastConductor_Reflow_Engine::calculate_reflow_layout($now_playing, 1280, 240, 1280, 720);
        
        $passed = isset($result[0]['_reflow']);
        $this->record_result('realWorld', 'Lower Third → Full Screen', $passed, true, $passed);

        // Scenario 2: No reflow needed (same container)
        $result2 = CastConductor_Reflow_Engine::calculate_reflow_layout($now_playing, 1280, 240, 1280, 240);
        $no_reflow = !isset($result2[0]['_reflow']);
        $this->record_result('realWorld', 'Same container - no reflow', $no_reflow, true, $no_reflow);

        echo "\n";
    }

    /**
     * Record a test result
     */
    private function record_result($category, $description, $passed, $expected, $actual) {
        $status = $passed ? '✓' : '✗';
        $color = $passed ? '32' : '31'; // Green or red

        echo "  {$status} {$description}";
        if (!$passed) {
            echo " (expected: {$expected}, got: {$actual})";
        }
        echo "\n";

        $this->test_results[] = [
            'category' => $category,
            'description' => $description,
            'passed' => $passed,
        ];
    }

    /**
     * Print test summary
     */
    private function print_summary() {
        $total = count($this->test_results);
        $passed = count(array_filter($this->test_results, fn($r) => $r['passed']));
        $failed = $total - $passed;

        echo "\n=== Test Summary ===\n";
        echo "Total: {$total} | Passed: {$passed} | Failed: {$failed}\n";

        if ($failed > 0) {
            echo "\nFailed tests:\n";
            foreach ($this->test_results as $result) {
                if (!$result['passed']) {
                    echo "  - [{$result['category']}] {$result['description']}\n";
                }
            }
        }

        echo "\n";
    }
}

// Run tests if executed directly
if (php_sapi_name() === 'cli' || (isset($_GET['run_tests']) && current_user_can('manage_options'))) {
    $test = new CastConductor_Reflow_Parity_Test();
    $test->run_all_tests();
}
