<?php

declare(strict_types=1);

namespace App\Framework\Discovery\Runtime;

use App\Framework\Discovery\Results\AttributeRegistry;
use App\Framework\Discovery\Results\DiscoveryRegistry;
use App\Framework\Discovery\Results\InterfaceRegistry;
use App\Framework\Discovery\Results\TemplateRegistry;
use App\Framework\Discovery\Storage\DiscoveryStorageService;

/**
 * Fast runtime loader for pre-discovered data
 *
 * Loads discovery results from storage instead of scanning files during bootstrap
 */
final readonly class DiscoveryLoader
{
    public function __construct(
        private DiscoveryStorageService $storage
    ) {
    }

    /**
     * Load all pre-discovered data for runtime use
     */
    public function loadAll(): DiscoveryRegistry
    {
        $attributes = $this->storage->loadAttributes() ?? new AttributeRegistry();
        $templates = $this->storage->loadTemplates() ?? new TemplateRegistry();
        $interfaces = $this->storage->loadInterfaces() ?? new InterfaceRegistry();

        return new DiscoveryRegistry(
            attributes: $attributes,
            templates: $templates,
            interfaces: $interfaces
        );
    }

    /**
     * Load only attributes (fastest for web requests)
     */
    public function loadAttributes(): AttributeRegistry
    {
        return $this->storage->loadAttributes() ?? new AttributeRegistry();
    }

    /**
     * Load only templates (for template engine)
     */
    public function loadTemplates(): TemplateRegistry
    {
        return $this->storage->loadTemplates() ?? new TemplateRegistry();
    }

    /**
     * Load only interfaces (for DI container)
     */
    public function loadInterfaces(): InterfaceRegistry
    {
        return $this->storage->loadInterfaces() ?? new InterfaceRegistry();
    }

    /**
     * Check if pre-discovered data exists
     */
    public function hasPreDiscoveredData(): bool
    {
        return $this->storage->exists('attributes')
            && $this->storage->exists('templates')
            && $this->storage->exists('interfaces');
    }

    /**
     * Get storage timestamps for cache invalidation
     */
    public function getStorageTimestamps(): array
    {
        return [
            'attributes' => $this->storage->getLastModified('attributes'),
            'templates' => $this->storage->getLastModified('templates'),
            'interfaces' => $this->storage->getLastModified('interfaces'),
        ];
    }
}
