<?php
defined('ABSPATH') || exit;

if (!class_exists('Aimogen_Thread')) {

class Aimogen_Thread {

    private $api;
    private $thread_id;

    public function __construct($api, $thread_id) {
        $this->api = $api;
        $this->thread_id = sanitize_key($thread_id);
    }

    public function say($message, $args = array()) {
        $key = 'aimogen_thread_' . md5($this->thread_id);
        $history = get_transient($key);

        if (!is_array($history)) {
            $history = array();
        }

        $history[] = array(
            'role'    => 'user',
            'content' => $message,
        );

        $limit = isset($args['history']) ? absint($args['history']) : 20;

        if ($limit > 0 && count($history) > $limit) {
            $history = array_slice($history, -$limit);
        }

        $args['is_chat'] = true;
        $args['env'] = isset($args['env']) ? $args['env'] : 'phpApiThread';

        $response = $this->api->run($history, $args);

        if ($response->ok()) {
            $history[] = array(
                'role'    => 'assistant',
                'content' => $response->text(),
            );

            set_transient($key, $history, DAY_IN_SECONDS * 7);
        }

        return $response;
    }

    public function id() {
        return $this->thread_id;
    }

    public function forget() {
        delete_transient('aimogen_thread_' . md5($this->thread_id));
    }
}

}