<?php
namespace boru\ai\Conversation;

use boru\ai\Schema\Message;
use boru\ai\Schema\Request;

class SummarizedHistoryReplayStrategy implements ReplayStrategyInterface
{
    /** @var int */
    protected $keepTurns;

    /** @var int */
    protected $summaryMaxChars;

    /** @var ConversationReplayService */
    protected $service;

    /** @var array */
    protected $options;

    public function __construct($keepTurns = 3, $summaryMaxChars = 4000, ConversationReplayService $service = null, array $options = array())
    {
        $this->keepTurns = (int)$keepTurns >= 0 ? (int)$keepTurns : 3;
        $this->summaryMaxChars = (int)$summaryMaxChars > 0 ? (int)$summaryMaxChars : 4000;
        $this->service = $service ? $service : new ConversationReplayService();
        $this->options = $options;
    }

    public function buildReplayMessages(Conversation $conversation, Request $currentRequest = null)
    {
        $messages = array();
        $turns = $conversation->turns();
        if (empty($turns)) {
            return $messages;
        }

        $splitIndex = count($turns) - $this->keepTurns;
        if ($splitIndex < 0) {
            $splitIndex = 0;
        }

        $olderTurns = array_slice($turns, 0, $splitIndex);
        $recentTurns = array_slice($turns, $splitIndex);

        $summary = $this->service->summarizeTurns($olderTurns, $this->summaryMaxChars);
        if ($summary !== '') {
            $messages[] = new Message('system', array($summary), array(
                'replay_strategy' => 'summarize_history',
                'kind' => 'history_summary',
            ));
        }

        foreach ($recentTurns as $turn) {
            if (!$turn instanceof Turn) {
                continue;
            }

            foreach ($this->service->messagesFromTurn($turn, $this->options) as $message) {
                $messages[] = $message;
            }
        }

        return $messages;
    }
}
