<?php

declare(strict_types=1);

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

use App\Framework\ErrorAggregation\ErrorAggregator;
use App\Framework\ErrorAggregation\Storage\InMemoryErrorStorage;
use App\Framework\Queue\InMemoryQueue;
use App\Framework\Cache\Cache;
use App\Framework\Cache\CacheIdentifier;
use App\Framework\Cache\CacheItem;
use App\Framework\Cache\CacheKey;
use App\Framework\Cache\CacheResult;
use App\Framework\Core\ValueObjects\Duration;
use App\Framework\Core\ValueObjects\Timestamp;
use App\Framework\DateTime\Clock;
use App\Framework\Exception\Core\DatabaseErrorCode;
use App\Framework\Exception\FrameworkException;
use App\Framework\Exception\ExceptionContext;
use App\Framework\Exception\RequestContext;
use App\Framework\Exception\SystemContext;
use App\Framework\Exception\ErrorHandlerContext;
use App\Framework\Logging\Logger;

// Create simple logger
$logger = new class implements Logger {
    public function emergency(string $message, array $context = []): void { echo "[EMERGENCY] {$message}\n"; print_r($context); }
    public function alert(string $message, array $context = []): void { echo "[ALERT] {$message}\n"; print_r($context); }
    public function critical(string $message, array $context = []): void { echo "[CRITICAL] {$message}\n"; print_r($context); }
    public function error(string $message, array $context = []): void { echo "[ERROR] {$message}\n"; print_r($context); }
    public function warning(string $message, array $context = []): void { echo "[WARNING] {$message}\n"; print_r($context); }
    public function notice(string $message, array $context = []): void { echo "[NOTICE] {$message}\n"; print_r($context); }
    public function info(string $message, array $context = []): void {
        echo "[INFO] {$message}\n";
        if (!empty($context)) {
            print_r($context);
        }
    }
    public function debug(string $message, array $context = []): void { echo "[DEBUG] {$message}\n"; print_r($context); }
    public function log(string $level, string $message, array $context = []): void { echo "[{$level}] {$message}\n"; print_r($context); }
};

// Create test cache
$cache = new class implements Cache {
    private array $data = [];

    public function get(CacheIdentifier ...$identifiers): CacheResult
    {
        $hits = [];
        $misses = [];
        foreach ($identifiers as $identifier) {
            $key = $identifier->toString();
            if (isset($this->data[$key])) {
                $value = $this->data[$key];
                $hits[$key] = $value instanceof CacheItem ? $value->value : $value;
            } else {
                $misses[] = $key;
            }
        }
        return new CacheResult($hits, $misses);
    }

    public function set(CacheItem ...$items): bool
    {
        foreach ($items as $item) {
            $this->data[$item->key->toString()] = $item;
        }
        return true;
    }

    public function has(CacheIdentifier ...$identifiers): array { return []; }
    public function forget(CacheIdentifier ...$identifiers): bool { return true; }
    public function clear(): bool { $this->data = []; return true; }
    public function remember(CacheKey $key, callable $callback, ?Duration $ttl = null): CacheItem
    {
        $keyStr = $key->toString();
        if (isset($this->data[$keyStr])) {
            return $this->data[$keyStr];
        }
        $value = $callback();
        $item = CacheItem::forSetting($key, $value, $ttl);
        $this->data[$keyStr] = $item;
        return $item;
    }
};

// Create test clock
$clock = new class implements Clock {
    public function now(): \DateTimeImmutable { return new \DateTimeImmutable(); }
    public function fromTimestamp(Timestamp $timestamp): \DateTimeImmutable { return $timestamp->toDateTime(); }
    public function fromString(string $dateTime, ?string $format = null): \DateTimeImmutable { return new \DateTimeImmutable($dateTime); }
    public function today(): \DateTimeImmutable { return new \DateTimeImmutable('today'); }
    public function yesterday(): \DateTimeImmutable { return new \DateTimeImmutable('yesterday'); }
    public function tomorrow(): \DateTimeImmutable { return new \DateTimeImmutable('tomorrow'); }
    public function time(): Timestamp { return Timestamp::now(); }
};

echo "Setting up ErrorAggregator with logger...\n";
$storage = new InMemoryErrorStorage();
$alertQueue = new InMemoryQueue();

$errorAggregator = new ErrorAggregator(
    storage: $storage,
    cache: $cache,
    clock: $clock,
    alertQueue: $alertQueue,
    logger: $logger  // Add logger to see what's happening
);

echo "\nCreating exception and context...\n";
$exception = FrameworkException::create(
    DatabaseErrorCode::QUERY_FAILED,
    'Test database query failed'
);

$exceptionContext = ExceptionContext::empty()
    ->withOperation('test_operation', 'TestComponent')
    ->withData([
        'test_key' => 'test_value',
        'original_exception' => $exception,
        'exception_message' => $exception->getMessage()
    ]);

$requestContext = RequestContext::fromGlobals();
$systemContext = SystemContext::current();

$errorHandlerContext = ErrorHandlerContext::create(
    $exceptionContext,
    $requestContext,
    $systemContext,
    ['http_status' => 500]
);

echo "\nProcessing error...NOW WE SHOULD SEE LOGGER OUTPUT:\n";
echo "===================================================\n";
$errorAggregator->processError($errorHandlerContext);

echo "\n\nChecking results...\n";
$recentEvents = $errorAggregator->getRecentEvents(10);
echo "Recent events: " . count($recentEvents) . "\n";

$activePatterns = $errorAggregator->getActivePatterns(10);
echo "Active patterns: " . count($activePatterns) . "\n";

if (count($activePatterns) > 0) {
    echo "SUCCESS: Pattern was created!\n";
} else {
    echo "ERROR: Pattern was NOT created!\n";
}
