<?php

namespace App\Http\Controllers;

use App\Agent\CampaignPerformanceChatAgent;
use App\Campaigns\CampaignPerformanceChatAnswer;
use App\Campaigns\CampaignPerformanceSuggestionReplyGuard;
use App\Campaigns\CampaignSuggestionReader;
use App\Support\Markdown;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Throwable;

class CampaignPerformanceChatController extends Controller
{
    private const SESSION_KEY = 'campaign_performance_chat';

    public function show(): View
    {
        return view('campaigns.performance-chat', [
            'pageTitle' => 'Campaign performance chat',
            'transcript' => $this->present(session(self::SESSION_KEY, [])),
        ]);
    }

    public function send(
        Request $request,
        CampaignPerformanceChatAgent $agent,
        CampaignPerformanceSuggestionReplyGuard $replies,
        CampaignSuggestionReader $suggestions,
    ): RedirectResponse|JsonResponse {
        $message = trim((string) $request->validate([
            'message' => ['required', 'string', 'max:4000'],
        ])['message']);

        $transcript = session(self::SESSION_KEY, []);
        $transcript[] = ['role' => 'user', 'text' => $message];
        $replies->forgetCurrent();
        $cached = $replies->cachedReply($message, $suggestions);

        try {
            $reply = $cached ?? trim((string) $agent->prompt($this->prompt($transcript))->text);
            $reply = CampaignPerformanceChatAnswer::humanizeStatusCodes($reply);
            $reply = $reply !== '' ? $reply : 'The campaign performance tools did not return a text response.';
        } catch (Throwable $exception) {
            report($exception);
            $reply = 'The campaign performance chat failed: '.$exception->getMessage();
        }

        if ($cached === null) {
            $replies->store($message, $reply);
        }

        $html = (string) Markdown::toHtml($reply, true);
        $transcript[] = ['role' => 'assistant', 'text' => $reply, 'html' => $html];
        session([self::SESSION_KEY => array_slice($transcript, -20)]);

        if ($request->expectsJson()) {
            return response()->json([
                'user' => $message,
                'html' => $html,
            ]);
        }

        return redirect()->route('campaigns.performance.chat');
    }

    public function reset(): RedirectResponse
    {
        session()->forget(self::SESSION_KEY);
        session()->forget(CampaignPerformanceSuggestionReplyGuard::SESSION_KEY);

        return redirect()->route('campaigns.performance.chat');
    }

    /**
     * @param  list<array{role: string, text: string, html?: string}>  $transcript
     * @return list<array{role: string, text: string, html?: string}>
     */
    private function present(array $transcript): array
    {
        return array_map(function (array $message): array {
            if (($message['role'] ?? '') !== 'assistant') {
                return $message;
            }

            $text = CampaignPerformanceChatAnswer::humanizeStatusCodes((string) ($message['text'] ?? ''));
            $message['text'] = $text;
            $message['html'] = (string) Markdown::toHtml($text, true);

            return $message;
        }, $transcript);
    }

    /**
     * @param  list<array{role: string, text: string, html?: string}>  $transcript
     */
    private function prompt(array $transcript): string
    {
        return collect($transcript)
            ->map(fn (array $message): string => strtoupper($message['role']).': '.$message['text'])
            ->implode("\n");
    }
}
