<?php

namespace Breakdance\AI;

use function Breakdance\Data\get_global_option;
use function Breakdance\Data\set_global_option;

add_action('breakdance_loaded', function () {
    \Breakdance\AJAX\register_handler(
        'breakdance_ai_get_settings',
        'Breakdance\AI\getSettings',
        getAiRole()
    );

    \Breakdance\AJAX\register_handler(
        'breakdance_ai_save_settings',
        'Breakdance\AI\saveSettings',
        getAiRole(),
        false,
        [
            'args' => [
                'settings' => FILTER_UNSAFE_RAW
            ]
        ]
    );

    \Breakdance\AJAX\register_handler(
        'breakdance_ai_persist_messages',
        'Breakdance\AI\persistMessages',
        getAiRole(),
        false,
        [
            'args' => [
                'messages' => FILTER_UNSAFE_RAW,
                'format' => FILTER_SANITIZE_SPECIAL_CHARS,
                'temperature' => FILTER_VALIDATE_FLOAT
            ],
            'optional_args' => [
                'temperature'
            ]
        ],
    );
});

/**
 * @param string $settings
 * @return array
 */
function saveSettings($settings) {
    $settings = json_decode($settings, true);
    set_global_option('ai_settings_json_string', $settings); // TODO: Security check
    return getSettings();
}

/**
 * @return array
 */
function getPromptSettings() {
    /** @var array $settings */
    $settings = get_global_option('ai_settings_json_string');

    $defaults = [
        'businessName' => get_bloginfo('name'),
        'businessDescription' => get_bloginfo('description'),
        'presets' => []
    ];

    return array_merge($defaults, $settings ?? []);
}

/**
 * @return array
 */
function getSettings() {
    return [
        'data' => [
            'isApiKeySet' => \Breakdance\APIKeys\getKey('openai') !== '',
            'isStreamingEnabled' => isStreamingEnabled(),
            'model' => getModel(),
            'prompt' => getPromptSettings(),
        ]
    ];
}

function persistMessages($message, $format, $temperature = null) {
    if (!session_id()) {
        session_start();
    }

    // Clear previous messages
    unset($_SESSION['breakdance_ai_messages']);
    unset($_SESSION['breakdance_ai_format']);
    unset($_SESSION['breakdance_ai_temperature']);

    // Persist new messages
    $_SESSION['breakdance_ai_messages'] = $message;
    $_SESSION['breakdance_ai_format'] = $format;

    if ($temperature) {
        $_SESSION['breakdance_ai_temperature'] = $temperature;
    }

    return ['status' => 'ok'];
}

function getPersistedMessages() {
    if (!session_id()) session_start();
    return $_SESSION['breakdance_ai_messages'] ?? '';
}

function getPersistedFormat() {
    if (!session_id()) session_start();
    return $_SESSION['breakdance_ai_format'] ?? '';
}

function getPersistedTemperature() {
    if (!session_id()) session_start();
    return $_SESSION['breakdance_ai_temperature'] ?? null;
}
