<?php

declare(strict_types=1);

require_once __DIR__ . '/../../vendor/autoload.php';

use App\Framework\DI\DefaultContainer;
use App\Framework\Filesystem\FilesystemInitializer;
use App\Framework\Filesystem\Storage;
use App\Framework\Filesystem\FileStorage;
use App\Framework\Filesystem\CachedFileStorage;
use App\Framework\Filesystem\FileValidator;
use App\Framework\Filesystem\CachedFileValidator;
use App\Framework\Core\PathProvider;

echo "Testing Filesystem DI Integration\n";
echo "==================================\n\n";

// Test 1: FileValidator with caching enabled (default)
echo "Test 1: FileValidator Resolution\n";
$_ENV['FILESYSTEM_VALIDATOR_CACHE'] = 'true';

// Create container
$container = new DefaultContainer();

// Register PathProvider dependency
$container->singleton(PathProvider::class, function() {
    return new PathProvider('/tmp');
});

// Initialize filesystem services
$initializer = new FilesystemInitializer();
$initializer->initializeFilesystem($container);
$validator = $container->get(FileValidator::class);
$isCached = $validator instanceof CachedFileValidator;
echo "  - Resolved: " . get_class($validator) . "\n";
echo "  - Is CachedFileValidator: " . ($isCached ? '✅ YES' : '❌ NO') . "\n";

if ($isCached) {
    echo "  - Cache TTL: " . ($_ENV['FILESYSTEM_VALIDATOR_CACHE_TTL'] ?? '60') . " seconds\n";
    echo "  - Cache Size: " . ($_ENV['FILESYSTEM_VALIDATOR_CACHE_SIZE'] ?? '100') . " entries\n";
}
echo "\n";

// Test 2: FileValidator with caching disabled
echo "Test 2: FileValidator Without Caching\n";
$_ENV['FILESYSTEM_VALIDATOR_CACHE'] = 'false';
$container2 = new DefaultContainer();
$container2->singleton(PathProvider::class, function() {
    return new PathProvider('/tmp');
});
$initializer2 = new FilesystemInitializer();
$initializer2->initializeFilesystem($container2);
$validator2 = $container2->get(FileValidator::class);
$isCached2 = $validator2 instanceof CachedFileValidator;
echo "  - Resolved: " . get_class($validator2) . "\n";
echo "  - Is CachedFileValidator: " . ($isCached2 ? '❌ YES (should be NO)' : '✅ NO') . "\n\n";

// Reset for remaining tests
$_ENV['FILESYSTEM_VALIDATOR_CACHE'] = 'true';

// Test 3: Storage with caching enabled (default)
echo "Test 3: Storage Resolution\n";
$_ENV['FILESYSTEM_STORAGE_CACHE'] = 'true';
$storage = $container->get(Storage::class);
$isCachedStorage = $storage instanceof CachedFileStorage;
echo "  - Resolved: " . get_class($storage) . "\n";
echo "  - Is CachedFileStorage: " . ($isCachedStorage ? '✅ YES' : '❌ NO') . "\n\n";

// Test 4: Storage with caching disabled
echo "Test 4: Storage Without Caching\n";
$_ENV['FILESYSTEM_STORAGE_CACHE'] = 'false';
$container3 = new DefaultContainer();
$container3->singleton(PathProvider::class, function() {
    return new PathProvider('/tmp');
});
$initializer3 = new FilesystemInitializer();
$initializer3->initializeFilesystem($container3);
$storage2 = $container3->get(Storage::class);
$isCachedStorage2 = $storage2 instanceof CachedFileStorage;
echo "  - Resolved: " . get_class($storage2) . "\n";
echo "  - Is CachedFileStorage: " . ($isCachedStorage2 ? '❌ YES (should be NO)' : '✅ NO') . "\n\n";

// Test 5: Named storages
echo "Test 5: Named Storage Resolution\n";
$_ENV['FILESYSTEM_STORAGE_CACHE'] = 'true';
$localStorage = $container->get('filesystem.storage.local');
$tempStorage = $container->get('filesystem.storage.temp');
$analyticsStorage = $container->get('filesystem.storage.analytics');

echo "  - Local Storage: " . get_class($localStorage) . "\n";
echo "  - Is CachedFileStorage: " . ($localStorage instanceof CachedFileStorage ? '✅ YES' : '❌ NO') . "\n";
echo "  - Temp Storage: " . get_class($tempStorage) . "\n";
echo "  - Is CachedFileStorage: " . ($tempStorage instanceof CachedFileStorage ? '✅ YES' : '❌ NO') . "\n";
echo "  - Analytics Storage: " . get_class($analyticsStorage) . "\n";
echo "  - Is CachedFileStorage: " . ($analyticsStorage instanceof CachedFileStorage ? '✅ YES' : '❌ NO') . "\n\n";

// Test 6: Functional test - validator caching works
echo "Test 6: Validator Caching Functionality\n";
$testValidator = $container->get(FileValidator::class);
if ($testValidator instanceof CachedFileValidator) {
    // First validation - cache miss
    try {
        $testValidator->validatePath('/safe/path/file.txt');
        echo "  - First validation: ✅ Success\n";
    } catch (\Exception $e) {
        echo "  - First validation: ❌ Failed - " . $e->getMessage() . "\n";
    }

    // Second validation - cache hit (should be faster)
    try {
        $testValidator->validatePath('/safe/path/file.txt');
        echo "  - Second validation (cached): ✅ Success\n";
    } catch (\Exception $e) {
        echo "  - Second validation: ❌ Failed - " . $e->getMessage() . "\n";
    }

    $stats = $testValidator->getCacheStats();
    echo "  - Cache hits: " . $stats['path_cache_hits'] . "\n";
    echo "  - Cache misses: " . $stats['path_cache_misses'] . "\n";
}
echo "\n";

// Test 7: Functional test - storage directory caching works
echo "Test 7: Storage Directory Caching Functionality\n";
$testStorage = $container->get(Storage::class);
if ($testStorage instanceof CachedFileStorage) {
    // Create test directory structure
    $testDir = sys_get_temp_dir() . '/fs_di_test_' . uniqid();
    mkdir($testDir, 0777, true);

    // First write - cache miss
    $testStorage->put($testDir . '/nested/deep/file1.txt', 'content1');
    echo "  - First write: ✅ Success\n";

    // Second write - cache hit
    $testStorage->put($testDir . '/nested/deep/file2.txt', 'content2');
    echo "  - Second write (cached directory): ✅ Success\n";

    $stats = $testStorage->getCacheStats();
    echo "  - Cached directories: " . $stats['cached_directories'] . "\n";

    // Cleanup
    function deleteDirectoryRecursive(string $dir): void {
        if (!is_dir($dir)) return;
        $files = array_diff(scandir($dir), ['.', '..']);
        foreach ($files as $file) {
            $path = $dir . '/' . $file;
            is_dir($path) ? deleteDirectoryRecursive($path) : unlink($path);
        }
        rmdir($dir);
    }
    deleteDirectoryRecursive($testDir);
}
echo "\n";

echo "==================================\n";
echo "All DI Integration Tests Complete\n";
echo "==================================\n";
