<?php

declare(strict_types=1);

namespace Plugin\tnt_mcp\src\Mcp\Admin;

use Plugin\tnt_mcp\src\Ai\AiStatus;

/**
 * "What do I do next?" — the checklist behind the Start tab (design §2).
 *
 * The plugin's first screen used to be Server-Status: mode badge, PHP version, OAuth key presence,
 * audit counters. Every one of those is true and none of them is an answer, so a merchant who had
 * just installed the plugin met a debug dashboard and had to guess which of six tabs to open.
 *
 * The rules this class encodes:
 *
 *   - **Order is the answer.** The steps are in the order they have to happen, and the FIRST
 *     incomplete one is the call to action. Anything below it is not the merchant's problem yet.
 *   - **Every incomplete step names the tab that fixes it.** A checklist that says "not done"
 *     without saying where is a nicer way of saying nothing.
 *   - **AI is optional and says so.** A shop can run the MCP server without ever configuring an
 *     LLM; a red cross next to something the merchant deliberately did not want is a false alarm.
 */
final class SetupChecklist
{
    public const STATE_DONE = 'done';

    public const STATE_TODO = 'todo';

    /** Done for the purpose of "can I use this", but worth mentioning — used by the AI row. */
    public const STATE_OPTIONAL = 'optional';

    /**
     * @param bool        $oauthKeysPresent whether the signing keys exist yet
     * @param int         $liveClients      OAuth clients holding at least one usable token
     * @param string|null $aiState          {@see AiStatus}'s verdict, or null when it cannot be read
     * @return list<array{key:string,state:string,title:string,detail:string,tab:string}>
     */
    public static function build(
        string $language,
        bool $oauthKeysPresent,
        int $liveClients,
        ?string $aiState,
    ): array {
        $steps = [];

        $steps[] = [
            'key'    => 'keys',
            'state'  => $oauthKeysPresent ? self::STATE_DONE : self::STATE_TODO,
            'title'  => AdminLanguage::pick([
                'de' => 'Sicherheitsschlüssel erzeugt',
                'en' => 'Security keys generated',
            ], $language),
            'detail' => $oauthKeysPresent
                ? ''
                : AdminLanguage::pick([
                    'de' => 'Die Schlüssel entstehen beim ersten Verbindungsversuch von selbst — '
                        . 'es ist nichts zu tun, solange kein Fehler gemeldet wird.',
                    'en' => 'The keys are created by themselves on the first connection attempt — '
                        . 'there is nothing to do unless an error is reported.',
                ], $language),
            'tab'    => '',
        ];

        $steps[] = [
            'key'    => 'client',
            'state'  => $liveClients > 0 ? self::STATE_DONE : self::STATE_TODO,
            'title'  => $liveClients > 0
                ? AdminLanguage::pick([
                    'de' => 'KI-Assistent verbunden',
                    'en' => 'AI assistant connected',
                ], $language)
                : AdminLanguage::pick([
                    'de' => 'KI-Assistenten verbinden',
                    'en' => 'Connect an AI assistant',
                ], $language),
            'detail' => $liveClients > 0
                ? AdminLanguage::pick([
                    'de' => \sprintf('%d aktive Verbindung(en).', $liveClients),
                    'en' => \sprintf('%d live connection(s).', $liveClients),
                ], $language)
                : AdminLanguage::pick([
                    'de' => 'Die MCP-Server-URL unten in ChatGPT oder Claude eintragen.',
                    'en' => 'Paste the MCP server URL below into ChatGPT or Claude.',
                ], $language),
            'tab'    => $liveClients > 0 ? 'Zugriff' : '',
        ];

        $steps[] = [
            'key'    => 'ai',
            'state'  => match ($aiState) {
                AiStatus::STATE_ACTIVE   => self::STATE_DONE,
                // Not "todo": the shop works without an LLM, and a merchant who never wanted one
                // must not be shown an outstanding task they will never complete.
                null, AiStatus::STATE_NONE => self::STATE_OPTIONAL,
                default                  => self::STATE_TODO,
            },
            'title'  => AdminLanguage::pick([
                'de' => 'KI-Anbindung des Shops',
                'en' => "The shop's own AI connection",
            ], $language),
            'detail' => AdminLanguage::pick([
                'de' => 'Optional — das Plugin läuft ohne KI-Anbieter. Ein API-Key wird nur '
                    . 'gebraucht, wenn der Shop SELBST eine KI befragen soll (WorkFlows, Snippets). '
                    . 'Für ChatGPT oder Claude von außen genügt die MCP-Verbindung.',
                'en' => 'Optional — the plugin runs without an AI provider. An API key is only '
                    . 'needed when the shop ITSELF should ask an AI (workflows, snippets). '
                    . 'Connecting ChatGPT or Claude from outside needs nothing but the MCP link.',
            ], $language),
            'tab'    => 'KI',
        ];

        return $steps;
    }

    /**
     * The first step that still needs the merchant, or null when everything that matters is done.
     * Optional steps never become the call to action.
     *
     * @param list<array{key:string,state:string,title:string,detail:string,tab:string}> $steps
     * @return array{key:string,state:string,title:string,detail:string,tab:string}|null
     */
    public static function nextStep(array $steps): ?array
    {
        foreach ($steps as $step) {
            if ($step['state'] === self::STATE_TODO) {
                return $step;
            }
        }

        return null;
    }
}
