<?php

namespace GriffinForms\Includes\Ai;

use GriffinForms\Includes\Ai\PromptRegistry\PromptRegistry;

class AssistSurfaceRegistry
{
    protected const SURFACES = [
        'form_builder' => [
            'surface' => 'form_builder',
            'label' => 'Form Builder',
            'presentation_mode' => 'docked_sidebar',
            'context_supported' => true,
            'chat_enabled' => true,
            'chat_mode_toggle' => true,
            'default_chat_mode' => false,
            'show_suggestions' => true,
            'overrides' => [
                'launcher_enabled' => false,
                'launcher_label' => 'Griffin Assist',
                'overlay_width' => '360px',
                'theme_variant' => 'builder',
            ],
            'required_prompt_keys' => [
                'advisory_response',
                'generate_foundation',
            ],
        ],
    ];

    public function get(string $surface): ?array
    {
        $surface = sanitize_key($surface);
        if ($surface === '' || !isset(self::SURFACES[$surface])) {
            return null;
        }

        $config = self::SURFACES[$surface];
        $config['surface'] = sanitize_key((string) ($config['surface'] ?? $surface));
        $config['presentation_mode'] = sanitize_key((string) ($config['presentation_mode'] ?? 'docked_sidebar'));
        $config['context_supported'] = !empty($config['context_supported']);
        $config['chat_enabled'] = !empty($config['chat_enabled']);
        $config['chat_mode_toggle'] = !empty($config['chat_mode_toggle']);
        $config['default_chat_mode'] = !empty($config['default_chat_mode']);
        $config['show_suggestions'] = !empty($config['show_suggestions']);
        $config['required_prompt_keys'] = array_values(array_filter(array_map('sanitize_key', (array) ($config['required_prompt_keys'] ?? []))));
        $config['overrides'] = is_array($config['overrides'] ?? null) ? $config['overrides'] : [];

        return $config;
    }

    public function canRender(string $surface, ?PromptRegistry $prompt_registry = null): bool
    {
        $config = $this->get($surface);
        if (!is_array($config)) {
            return false;
        }

        if (empty($config['chat_enabled']) || empty($config['context_supported'])) {
            return false;
        }

        if ($prompt_registry === null) {
            return true;
        }

        foreach ((array) ($config['required_prompt_keys'] ?? []) as $prompt_key) {
            if (!$prompt_registry->has((string) $prompt_key)) {
                return false;
            }
        }

        return true;
    }
}
