<?php
/**
 * Fix GuzzleHttp Namespace Issues
 * This script fixes incorrect namespaces in GuzzleHttp vendor files
 * Run this via command line: php fix-guzzle-namespaces.php
 */

if (php_sapi_name() !== 'cli' && !defined('WP_CLI')) {
    // Allow running from WordPress if needed
    if (!defined('ABSPATH')) {
        // Try to find WordPress
        $wpLoadPath = dirname(dirname(dirname(dirname(__FILE__)))) . '/wp-load.php';
        if (file_exists($wpLoadPath)) {
            require_once $wpLoadPath;
        } else {
            die("This script must be run from command line or WordPress\n");
        }
    }
}

$pluginPath = __DIR__;
$guzzlePath = $pluginPath . '/vendor/guzzlehttp/guzzle/src';

if (!is_dir($guzzlePath)) {
    die("GuzzleHttp directory not found: $guzzlePath\n");
}

echo "Fixing GuzzleHttp namespaces...\n";

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($guzzlePath, RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::SELF_FIRST
);

$fixedCount = 0;
$filesToFix = [];

// First pass: collect all files that need fixing
foreach ($iterator as $file) {
    if ($file->isFile() && $file->getExtension() === 'php') {
        $filePath = $file->getRealPath();
        $content = file_get_contents($filePath);
        
        // Check if namespace has incorrect path (guzzle\src in namespace)
        if (preg_match('/^namespace\s+PYS_PRO_GLOBAL\\\\GuzzleHttp\\\\guzzle\\\\src/m', $content)) {
            $filesToFix[] = $filePath;
        }
    }
}

echo "Found " . count($filesToFix) . " files to fix.\n\n";

// Second pass: fix each file
foreach ($filesToFix as $filePath) {
    $content = file_get_contents($filePath);
    $originalContent = $content;
    
    // Get relative path from guzzle/src
    $relativePath = str_replace($guzzlePath . DIRECTORY_SEPARATOR, '', $filePath);
    $relativePath = str_replace(DIRECTORY_SEPARATOR, '\\', $relativePath);
    $relativePath = str_replace('.php', '', $relativePath);
    
    // Get directory path (without filename)
    $dirPath = dirname($relativePath);
    
    // Build correct namespace
    if ($dirPath === '.' || $dirPath === '') {
        // File is directly in src/ directory
        $correctNamespace = 'PYS_PRO_GLOBAL\\GuzzleHttp';
    } else {
        // File is in a subdirectory (e.g., Handler, Exception, Cookie)
        $correctNamespace = 'PYS_PRO_GLOBAL\\GuzzleHttp\\' . str_replace('\\', '\\', $dirPath);
    }
    
    // Fix namespace declaration - match the full incorrect namespace
    $content = preg_replace(
        '/^namespace\s+PYS_PRO_GLOBAL\\\\GuzzleHttp\\\\guzzle\\\\src[^;]*;/m',
        'namespace ' . $correctNamespace . ';',
        $content
    );
    
    // Also fix any use statements that reference the wrong namespace
    $content = preg_replace(
        '/use\s+PYS_PRO_GLOBAL\\\\GuzzleHttp\\\\guzzle\\\\src\\\\/m',
        'use PYS_PRO_GLOBAL\\GuzzleHttp\\',
        $content
    );
    
    // Fix use statements for subdirectories (e.g., Handler, Exception)
    $content = preg_replace(
        '/use\s+PYS_PRO_GLOBAL\\\\GuzzleHttp\\\\guzzle\\\\src\\(Handler|Exception|Cookie)\\\\/m',
        'use PYS_PRO_GLOBAL\\GuzzleHttp\\$1\\',
        $content
    );
    
    if ($content !== $originalContent) {
        file_put_contents($filePath, $content);
        $fixedCount++;
        $relativeDisplay = str_replace($guzzlePath . DIRECTORY_SEPARATOR, '', $filePath);
        echo "✓ Fixed: $relativeDisplay\n";
    }
}

echo "\n✓ Total files fixed: $fixedCount\n";
echo "✓ Namespace fix completed!\n";
