<?php

namespace App\Agent\Tools;

use App\Agent\Choices;
use App\Agent\Workspace;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;

/** Offers a short clarification as clickable answers without changing campaign state. */
class OfferClarification implements Tool
{
    public function __construct(
        private readonly Choices $choices,
        private readonly Workspace $workspace,
    ) {}

    public function description(): Stringable|string
    {
        return 'Show a clarification question with two to four mutually exclusive answers as clickable choices. '
            .'Use when the user must distinguish meanings, such as whether $10 means the total for 14 days or $10 per day. '
            .'An Other choice is added automatically and focuses the chat input for a typed answer. '
            .'This only asks; it never changes a campaign. Use a domain tool instead when it already offers supported settings.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'question' => $schema->string()->description('The concise question to show above the answers.')->required(),
            'options' => $schema->array()->items($schema->string())
                ->description('Two to four distinct answer labels. Do not include Other; it is added automatically.')
                ->required(),
        ];
    }

    public function handle(Request $request): Stringable|string
    {
        $arguments = $request->all();
        $question = trim((string) ($arguments['question'] ?? ''));
        $options = $arguments['options'] ?? [];

        if ($question === '' || mb_strlen($question) > 240 || ! is_array($options)
            || count($options) < 2 || count($options) > 4) {
            return json_encode(['ok' => false, 'error' => 'Provide one concise question and two to four answers.']);
        }

        $labels = [];

        foreach ($options as $option) {
            if (! is_string($option) || trim($option) === '' || mb_strlen(trim($option)) > 160) {
                return json_encode(['ok' => false, 'error' => 'Each answer must be a short, nonempty label.']);
            }

            $labels[] = trim($option);
        }

        $normalized = array_map(mb_strtolower(...), $labels);

        if (count(array_unique($normalized)) !== count($labels) || in_array('other', $normalized, true)) {
            return json_encode(['ok' => false, 'error' => 'Answers must be distinct; Other is added automatically.']);
        }

        if ($repeat = $this->alreadyAsked($question, $labels)) {
            return $repeat;
        }

        $this->choices->offer(
            field: 'clarification',
            question: $question,
            options: array_map(fn (string $label): array => [
                'value' => $label,
                'label' => $label,
                'sends' => $label,
            ], $labels),
            allowOther: true,
            otherInComposer: true,
        );

        return json_encode(['ok' => true, 'note' => 'The choices are on screen. Ask one short line and wait for the user.']);
    }

    /**
     * The same question, with the same answers, asked again.
     *
     * The user has typed something the model could not place, and the only
     * move it has is to ask - so it asks the identical question with the
     * identical options, and the conversation stops moving. Seen on 12 Oct:
     * "give me a list of campaigns and adsets in autoautomotive account" was
     * answered with "Which ad account would you like to check?" and two
     * options; the reply "auto automotive" produced that same question and
     * those same two options again. Nothing told the buyer that the account
     * they had named twice was not one this instance can reach.
     *
     * Deterministic rather than a prompt rule, because a prompt rule is advice
     * and this is a loop: the turn that repeats the question is the turn that
     * had already failed to answer it.
     *
     * Only an exact repeat is refused. The same question with a different set
     * of answers is progress - the model widening a two-option list to the
     * full one is the fix, not the fault - and a question asked again much
     * later is not caught at all, because only the last turn's offer is held.
     *
     * @param  list<string>  $labels
     */
    private function alreadyAsked(string $question, array $labels): ?string
    {
        $previous = null;

        foreach ($this->workspace->pendingChoices() as $choice) {
            if (($choice['field'] ?? null) === 'clarification') {
                $previous = $choice;

                break;
            }
        }

        if ($previous === null) {
            return null;
        }

        $asked = $this->same((string) ($previous['question'] ?? ''), $question);

        // Read defensively: this is a JSON column, and its shape has changed
        // before - the focus stamp in rememberChoices() was added after rows
        // already existed. A row written by an older build must not turn a
        // tool call into a type error and take the turn down with it.
        $offered = [];

        foreach ((array) ($previous['options'] ?? []) as $option) {
            if (is_array($option)) {
                $offered[] = (string) ($option['label'] ?? $option['value'] ?? '');
            }
        }

        if (! $asked || ! $this->sameSet($offered, $labels)) {
            return null;
        }

        return json_encode([
            'ok' => false,
            'error' => 'You asked this question last turn, with these same answers, and the user has replied. '
                .'Asking it again unchanged tells them nothing.',
            'they_said' => $this->workspace->saidByUser(1)[0] ?? null,
            'you_offered' => $offered,
            'note' => 'What they said matched none of the answers you gave. Say back what they asked for, say '
                .'plainly that it is not one of these, and name what is actually available. If it is something '
                .'that could exist but is not reachable here, say what would make it reachable. Answer in '
                .'prose - do not call this tool again with the same question.',
        ]);
    }

    /** Same question, ignoring case, surrounding space and a trailing question mark. */
    private function same(string $a, string $b): bool
    {
        $reduce = static fn (string $v): string => rtrim(mb_strtolower(trim($v)), '?');

        return $reduce($a) !== '' && $reduce($a) === $reduce($b);
    }

    /**
     * The same answers, in any order.
     *
     * @param  list<string>  $a
     * @param  list<string>  $b
     */
    private function sameSet(array $a, array $b): bool
    {
        $reduce = static function (array $values): array {
            $values = array_map(static fn (string $v): string => mb_strtolower(trim($v)), $values);
            sort($values);

            return $values;
        };

        return $a !== [] && $reduce($a) === $reduce($b);
    }
}
