<?php

declare(strict_types=1);

namespace App\Framework\TypeCaster;

use App\Framework\Core\ValueObjects\ClassName;
use App\Framework\DI\Container;
use App\Framework\Exception\FrameworkException;

/**
 * Registry for type casters - universal across the framework
 */
final class TypeCasterRegistry
{
    /** @var array<string, TypeCasterInterface> */
    private array $casters = [];

    /** @var array<string, TypeCasterInterface> Cache: type => caster */
    private array $typeCache = [];

    private bool $discovered = false;

    public function __construct(
        private readonly Container $container
    ) {
        $this->discoverCasters();
    }

    /**
     * Register a type caster
     */
    public function register(string $casterClass, TypeCasterInterface $caster): void
    {
        $this->casters[$casterClass] = $caster;
        // Clear type cache when new caster is registered
        $this->typeCache = [];
    }

    /**
     * Get caster by class name
     */
    public function get(string $casterClass): TypeCasterInterface
    {
        if (! isset($this->casters[$casterClass])) {
            // Auto-load if caster not yet registered
            if (! empty($casterClass) && ClassName::create($casterClass)->exists() && is_subclass_of($casterClass, TypeCasterInterface::class)) {
                $this->casters[$casterClass] = $this->container->get($casterClass);
            } else {
                throw new FrameworkException("Type caster {$casterClass} not found or invalid");
            }
        }

        return $this->casters[$casterClass];
    }

    /**
     * Check if caster exists
     */
    public function has(string $casterClass): bool
    {
        return isset($this->casters[$casterClass]) ||
               (! empty($casterClass) && ClassName::create($casterClass)->exists() && is_subclass_of($casterClass, TypeCasterInterface::class));
    }

    /**
     * Find the appropriate caster for a type
     */
    public function getCasterForType(string $type): ?TypeCasterInterface
    {
        if (! $this->discovered) {
            $this->discoverCasters();
        }

        // Check cache first
        if (isset($this->typeCache[$type])) {
            return $this->typeCache[$type];
        }

        // Find supporting caster
        foreach ($this->casters as $caster) {
            if ($caster->supports($type)) {
                // Cache for next time
                $this->typeCache[$type] = $caster;

                return $caster;
            }
        }

        return null;
    }

    /**
     * Convert string to Value Object using appropriate caster
     */
    public function fromString(string $value, string $type): mixed
    {
        $caster = $this->getCasterForType($type);

        if ($caster === null) {
            throw new FrameworkException("No caster found for type: {$type}");
        }

        return $caster->fromString($value);
    }

    /**
     * Convert Value Object to string using appropriate caster
     */
    public function toString(mixed $value, string $type): string
    {
        $caster = $this->getCasterForType($type);

        if ($caster === null) {
            throw new FrameworkException("No caster found for type: {$type}");
        }

        return $caster->toString($value);
    }

    /**
     * Get regex pattern for a type
     */
    public function getPattern(string $type): string
    {
        $caster = $this->getCasterForType($type);

        if ($caster === null) {
            // Default pattern for unknown types
            return '[^/]+';
        }

        return $caster->getPattern();
    }

    /**
     * Discover all available TypeCasters
     */
    private function discoverCasters(): void
    {
        // Discover from Framework TypeCaster module
        $this->discoverFromNamespace('App\\Framework\\TypeCaster\\Casters\\', __DIR__ . '/Casters');

        // Also discover from Database module for backward compatibility
        $databaseCasterPath = dirname(__DIR__) . '/Database/TypeCaster';
        if (is_dir($databaseCasterPath)) {
            $this->discoverFromNamespace('App\\Framework\\Database\\TypeCaster\\', $databaseCasterPath);
        }

        $this->discovered = true;
    }

    /**
     * Discover casters from a specific namespace and directory
     */
    private function discoverFromNamespace(string $namespace, string $directory): void
    {
        if (! is_dir($directory)) {
            return;
        }

        $files = glob($directory . '/*.php');
        if ($files === false) {
            return;
        }

        foreach ($files as $file) {
            $className = pathinfo($file, PATHINFO_FILENAME);
            $fullClassName = $namespace . $className;

            // Skip interfaces, registries, and abstract classes
            if (str_ends_with($className, 'Interface') ||
                str_ends_with($className, 'Registry') ||
                ! class_exists($fullClassName)) {
                continue;
            }

            $reflection = new \ReflectionClass($fullClassName);
            if ($reflection->isAbstract() || ! $reflection->implementsInterface(TypeCasterInterface::class)) {
                continue;
            }

            try {
                $this->casters[$fullClassName] = $this->container->get($fullClassName);
            } catch (\Exception) {
                // Caster couldn't be instantiated, skip
            }
        }
    }

    /**
     * Get all registered casters
     *
     * @return array<string, TypeCasterInterface>
     */
    public function getAllCasters(): array
    {
        if (! $this->discovered) {
            $this->discoverCasters();
        }

        return $this->casters;
    }
}
