<?php

namespace Breakdance\AI;

use Orhanerday\OpenAi\OpenAi;
use function Breakdance\Data\get_global_option;
use function Breakdance\Data\set_global_option;
use function Breakdance\Permissions\hasMinimumPermission;

function getOpenAi($key) {
    $open_ai = new OpenAi($key);
    $origin  = apply_filters('breakdance_ai_api_endpoint', 'https://api.openai.com');
    $open_ai->setCustomURL($origin);
    return $open_ai;
}

function getModel() {
    $model = get_global_option('ai_model');
    $model_versions = [
        'gpt-4' => 'gpt-4o',
        'gpt-4o' => 'gpt-4o',
    ];

    $model_version = $model_versions[$model] ?? 'gpt-4o-mini';

    return apply_filters('breakdance_ai_model', $model_version, $model);
}

function setModel($model) {
    set_global_option('ai_model', $model);
}

function getAiRole() {
    $role = get_global_option('ai_role');
    return ($role === false || $role === null) ? 'edit' : $role;
}

function setAiRole($role) {
    set_global_option('ai_role', $role);
}

function isStreamingEnabled() {
    return apply_filters(
        'breakdance_ai_streaming_enabled',
        true
    );
}


function getSuggestionsPrompt() {
    return apply_filters(
        'breakdance_ai_suggestions_prompt',
        '
Return an JSON array of 4 suggested prompts for the element name provided by the user.

The suggested prompts should CSS-related, relevant to the type of the element, and in imperative form. 

Below are listed a few examples of suggestions I\'d make in your place.
You are required to come up with your own prompts.

If the element name is "div":
- Stack content vertically
- Stack content horizontally
- Prevent it from wrapping
- Add a fade in animation

If the element name is "img":
- Scale on hover
- Add a border on hover
- Add a grayscale filter
- Add a sepia filter

If the element name is "button":
- Add a hover effect
- Add a background color
- Make it round
- Make it a ghost button

If the element name is "heading":
- Add a stroke effect
- Add a shadow
- Make it stand out

The JSON should be compatible with the TypeScript type Response from the following:
interface PromptResponse {
    prompts: string[];
}
'
    );
}

function disableAiIfNotEnoughPermissions($enabled) {
    $role = getAiRole();

    if (!hasMinimumPermission($role)) {
        return false;
    }

    return $enabled;
}

add_filter('breakdance_ai_enabled', '\Breakdance\AI\disableAiIfNotEnoughPermissions');
