<?php

namespace Mtc\Plugins\Agent\Agents\History;

use Illuminate\Support\Facades\Log;
use Mtc\Plugins\Agent\Models\AIChatHistory;
use NeuronAI\Chat\History\AbstractChatHistory;
use NeuronAI\Chat\History\ChatHistoryInterface;
use NeuronAI\Chat\Messages\Message;

class DatabaseChatHistory extends AbstractChatHistory
{
    public function __construct(
        protected string $sessionId,
        protected int $contextWindow = 50000
    ) {
        parent::__construct($contextWindow);
        $this->load();
    }

    /**
     * Load existing messages from the database into the $this->history array.
     */
    protected function load(): void
    {
        $record = AIChatHistory::where('guest_id', $this->sessionId)->first();

        if ($record && $record->messages) {
            // deserializeMessages is a helper in AbstractChatHistory
            // that converts raw arrays back into UserMessage/AssistantMessage objects
            $this->history = $this->deserializeMessages(json_decode($record->messages, true));
        }
    }

    /**
     * Save the current state of history back to the database.
     * This is called automatically by the Agent after every turn if using withChatHistory().
     */
    public function setMessages(array $messages): ChatHistoryInterface
    {
        // $this->jsonSerialize() converts Message objects to arrays
        $json = json_encode($this->jsonSerialize());

        Log::debug('Saving chat history for session: ' . $this->sessionId);

        AIChatHistory::updateOrCreate(
            ['guest_id' => $this->sessionId],
            ['messages' => $json]
        );

        return $this;
    }

    /**
     * Clear history (optional, but required by interface)
     */
    protected function clear(): ChatHistoryInterface
    {
        AIChatHistory::where('guest_id', $this->sessionId)->delete();
        $this->history = [];
        return $this;
    }
}
