<?php

/**
 * LolaCore — Hub Provider Service
 *
 * @package LolaCore
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\Hub;

use LolaCore\Admin\Settings;
use LolaCore\LLM\SelectedModelResolver;
use WordPress\AiClient\AiClient;
use WP_Error;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Applies fleet provider policy to the child site's Connectors settings (sprint C3 / E9.2).
 */
final class HubProviderService
{
    /**
     * @param array<string, mixed> $input
     * @return array<string, mixed>|WP_Error
     */
    public function apply(array $input): array|WP_Error
    {
        $provider = sanitize_key((string) ($input['provider'] ?? ''));
        $model    = sanitize_text_field((string) ($input['model'] ?? ''));

        if (! empty($input['dry_run'])) {
            return [
                'preview'  => true,
                'provider' => $provider,
                'model'    => $model,
                'message'  => __('Provider change preview only — nothing was saved.', 'lolacore'),
            ];
        }

        if ($provider === '' || $model === '') {
            return new WP_Error(
                'lolacore_hub_provider_missing_fields',
                __('Both provider and model are required.', 'lolacore'),
                ['status' => 400]
            );
        }

        if (! class_exists(AiClient::class)) {
            return [
                'applied' => false,
                'noop'    => true,
                'reason'  => 'connectors_unavailable',
                'message' => __('WordPress AI Connectors are not available on this site.', 'lolacore'),
            ];
        }

        try {
            $registry = AiClient::defaultRegistry();
            $registry->getProviderClassName($provider);
        } catch (\Throwable $e) {
            return new WP_Error(
                'lolacore_hub_provider_invalid',
                sprintf(
                    /* translators: %s: provider slug */
                    __('The provider "%s" is not registered in Connectors.', 'lolacore'),
                    $provider
                ),
                ['status' => 400]
            );
        }

        $previous = Settings::getConfig('selected_model', 'auto');
        Settings::setConfig('selected_model', $provider . '|' . $model);

        $resolved = null;
        try {
            $resolved = SelectedModelResolver::fromConfig($provider . '|' . $model);
        } catch (\Throwable $e) {
            $resolved = [
                'provider' => $provider,
                'model'    => $model,
            ];
        }

        return [
            'applied'          => true,
            'noop'             => false,
            'provider'         => (string) ($resolved['provider'] ?? $provider),
            'model'            => (string) ($resolved['model'] ?? $model),
            'previous_setting' => (string) $previous,
            'message'          => __('Provider updated for local Lola chat.', 'lolacore'),
        ];
    }
}
