<?php
/**
 * Tones REST API Endpoint.
 *
 * @package BoostBot
 * @since   1.0.0
 */

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Class BoostBot_Tones_Endpoint
 *
 * Handles REST API endpoints for personality tones.
 *
 * @since 1.0.0
 */
class BoostBot_Tones_Endpoint extends BoostBot_Base_Endpoint {

    /**
     * REST base for this endpoint.
     *
     * @var string
     */
    protected $rest_base = 'tones';

    /**
     * Register routes for this endpoint.
     *
     * @return void
     */
    public function register() {
        // GET /tones - List all tones
        $this->register_route(
            '',
            'GET',
            array( $this, 'get_tones' ),
            array( $this, 'admin_access' )
        );

        // POST /tones - Create tone
        $this->register_route(
            '',
            'POST',
            array( $this, 'create_tone' ),
            array( $this, 'admin_access' )
        );

        // GET /tones/{id} - Get single tone
        $this->register_route(
            '/(?P<id>\d+)',
            'GET',
            array( $this, 'get_tone' ),
            array( $this, 'admin_access' )
        );

        // PUT /tones/{id} - Update tone
        $this->register_route(
            '/(?P<id>\d+)',
            'PUT',
            array( $this, 'update_tone' ),
            array( $this, 'admin_access' )
        );

        // DELETE /tones/{id} - Delete tone
        $this->register_route(
            '/(?P<id>\d+)',
            'DELETE',
            array( $this, 'delete_tone' ),
            array( $this, 'admin_access' )
        );

        // POST /tones/generate-prompt - Generate system prompt for tone
        $this->register_route(
            '/generate-prompt',
            'POST',
            array( $this, 'generate_prompt' ),
            array( $this, 'admin_access' )
        );

        // POST /tones/improve-prompt - Improve existing system prompt
        $this->register_route(
            '/improve-prompt',
            'POST',
            array( $this, 'improve_prompt' ),
            array( $this, 'admin_access' )
        );
    }

    /**
     * Get all tones.
     *
     * @param WP_REST_Request $request The request.
     * @return WP_REST_Response
     */
    public function get_tones( $request ) {
        $model = new BoostBot_Tone_Model();

        if ( $request->has_param( 'language' ) ) {
            $tones = $model->get_all( array(
                'where'   => array( 'is_active' => 1, 'language' => $request->get_param( 'language' ) ),
                'orderby' => 'is_system',
                'order'   => 'DESC',
                'limit'   => 200,
            ) );
        } else {
            $tones = $model->get_active();
        }

        return $this->success( array( 'tones' => $tones ) );
    }

    /**
     * Get a single tone.
     *
     * @param WP_REST_Request $request The request.
     * @return WP_REST_Response|WP_Error
     */
    public function get_tone( $request ) {
        $id    = absint( $request->get_param( 'id' ) );
        $model = new BoostBot_Tone_Model();

        $tone = $model->get( $id );
        if ( ! $tone ) {
            return $this->not_found( 'Tone' );
        }

        return $this->success( array( 'tone' => $tone ) );
    }

    /**
     * Create new tone.
     *
     * @param WP_REST_Request $request The request.
     * @return WP_REST_Response|WP_Error
     */
    public function create_tone( $request ) {
        $model = new BoostBot_Tone_Model();
        $data  = $request->get_json_params();

        // Generate slug if not provided
        if ( empty( $data['slug'] ) && ! empty( $data['name'] ) ) {
            $data['slug'] = sanitize_title( $data['name'] );
        }

        // Set default values
        if ( ! isset( $data['is_active'] ) ) {
            $data['is_active'] = 1;
        }
        if ( ! isset( $data['is_system'] ) ) {
            $data['is_system'] = 0;
        }

        $id = $model->create( $data );

        if ( is_wp_error( $id ) ) {
            return $this->error( $id->get_error_message(), 400 );
        }

        if ( ! $id ) {
            return $this->error( __( 'Failed to create tone', 'boostbot' ), 400 );
        }

        $tone = $model->get( $id );

        if ( class_exists( 'BoostBot_Logger' ) ) {
            BoostBot_Logger::info( 'Tone created', array( 'id' => $id, 'name' => $data['name'] ?? '' ) );
        }

        return $this->success( array(
            'tone'    => $tone,
            'message' => __( 'Tone created successfully', 'boostbot' ),
        ), 201 );
    }

    /**
     * Update tone.
     *
     * @param WP_REST_Request $request The request.
     * @return WP_REST_Response|WP_Error
     */
    public function update_tone( $request ) {
        $id    = absint( $request->get_param( 'id' ) );
        $model = new BoostBot_Tone_Model();

        $existing = $model->get( $id );
        if ( ! $existing ) {
            return $this->not_found( 'Tone' );
        }

        $data   = $request->get_json_params();
        $result = $model->update( $id, $data );

        if ( ! $result ) {
            return $this->error( __( 'Failed to update tone', 'boostbot' ), 400 );
        }

        $tone = $model->get( $id );

        if ( class_exists( 'BoostBot_Logger' ) ) {
            BoostBot_Logger::info( 'Tone updated', array( 'id' => $id ) );
        }

        return $this->success( array(
            'tone'    => $tone,
            'message' => __( 'Tone updated successfully', 'boostbot' ),
        ) );
    }

    /**
     * Delete tone.
     *
     * @param WP_REST_Request $request The request.
     * @return WP_REST_Response|WP_Error
     */
    public function delete_tone( $request ) {
        $id    = absint( $request->get_param( 'id' ) );
        $model = new BoostBot_Tone_Model();

        // Check if can delete
        $can_delete = $model->can_delete( $id );
        if ( is_wp_error( $can_delete ) ) {
            return $this->error( $can_delete->get_error_message(), 403 );
        }

        $result = $model->delete( $id );

        if ( ! $result ) {
            return $this->error( __( 'Failed to delete tone', 'boostbot' ), 400 );
        }

        if ( class_exists( 'BoostBot_Logger' ) ) {
            BoostBot_Logger::info( 'Tone deleted', array( 'id' => $id ) );
        }

        return $this->success( array(
            'message' => __( 'Tone deleted successfully', 'boostbot' ),
        ) );
    }

    /**
     * Generate system prompt for a new tone using AI.
     *
     * @param WP_REST_Request $request The request.
     * @return WP_REST_Response|WP_Error
     */
    public function generate_prompt( $request ) {
        $data = $request->get_json_params();

        $tone_name = sanitize_text_field( $data['name'] ?? '' );
        $tone_description = sanitize_text_field( $data['description'] ?? '' );
        $language = sanitize_text_field( $data['language'] ?? '' );

        if ( '' === $language && class_exists( 'BoostBot_Language' ) ) {
            $language = BoostBot_Language::get_primary();
        }

        if ( empty( $tone_name ) ) {
            return $this->error( __( 'Tone name is required', 'boostbot' ), 400 );
        }

        try {
            if ( ! class_exists( 'BoostBot_Backend_AI_Client' ) ) {
                throw new Exception( 'Backend AI client not available.' );
            }
            $ai_client = new BoostBot_Backend_AI_Client();

            if ( 'en' === $language ) {
                $prompt = "You are an expert at creating System Prompts for customer service chatbots.

Create a System Prompt in English for a bot with the following tone:
Tone name: {$tone_name}
" . ( $tone_description ? "Description: {$tone_description}" : '' ) . "

The System Prompt should include:
1. Personality and general tone definition
2. Behavioral guidelines (4-6 points)
3. Communication style (3-4 points)

Requirements:
- Write in English
- Focus on the specific tone requested
- Be specific and practical
- Do not include unnecessary tags or headers at the beginning of the prompt
- The prompt should be 150-250 words long

Provide only the System Prompt itself, no additional explanations.";
            } else {
                $prompt = "אתה מומחה ליצירת הנחיות מערכת (System Prompts) לבוטים של שירות לקוחות.

צור System Prompt בעברית עבור בוט עם הטון הבא:
שם הטון: {$tone_name}
" . ( $tone_description ? "תיאור: {$tone_description}" : '' ) . "

ה-System Prompt צריך לכלול:
1. הגדרת האישיות והטון הכללי
2. הנחיות התנהגות (4-6 נקודות)
3. סגנון תקשורת (3-4 נקודות)

דרישות:
- כתוב בעברית
- התמקד בטון הספציפי שביקשו
- היה ספציפי ומעשי
- אל תכלול תגים או כותרות מיותרות בתחילת הפרומפט
- הפרומפט צריך להיות באורך של 150-250 מילים

תן רק את ה-System Prompt עצמו, ללא הסברים נוספים.";
            }

            $response = $ai_client->send_message(
                array(
                    array(
                        'role'    => 'user',
                        'content' => $prompt,
                    ),
                ),
                array(
                    'max_tokens'  => 1024,
                    'temperature' => 0.7,
                )
            );

            $system_prompt = trim( (string) ( $response['content'] ?? '' ) );
            if ( '' === $system_prompt ) {
                throw new Exception( 'Empty response from AI generation.' );
            }

            return $this->success( array(
                'system_prompt' => $system_prompt,
                'message'       => __( 'System prompt generated successfully', 'boostbot' ),
            ) );

        } catch ( Exception $e ) {
            if ( class_exists( 'BoostBot_Logger' ) ) {
                BoostBot_Logger::error( 'Failed to generate tone prompt', array(
                    'error' => $e->getMessage(),
                ) );
            }

            return $this->error( __( 'Failed to generate system prompt: ', 'boostbot' ) . $e->getMessage(), 500 );
        }
    }

    /**
     * Improve existing system prompt using AI.
     *
     * @param WP_REST_Request $request The request.
     * @return WP_REST_Response|WP_Error
     */
    public function improve_prompt( $request ) {
        $data = $request->get_json_params();

        $current_prompt = sanitize_textarea_field( $data['current_prompt'] ?? '' );
        $tone_name = sanitize_text_field( $data['tone_name'] ?? '' );
        $improvement_type = sanitize_text_field( $data['improvement_type'] ?? 'general' );
        $language = sanitize_text_field( $data['language'] ?? '' );

        if ( '' === $language && class_exists( 'BoostBot_Language' ) ) {
            $language = BoostBot_Language::get_primary();
        }

        if ( empty( $current_prompt ) ) {
            return $this->error( __( 'Current prompt is required', 'boostbot' ), 400 );
        }

        try {
            if ( ! class_exists( 'BoostBot_Backend_AI_Client' ) ) {
                throw new Exception( 'Backend AI client not available.' );
            }
            $ai_client = new BoostBot_Backend_AI_Client();

            if ( 'en' === $language ) {
                $improvement_instructions = array(
                    'general'      => 'Improve the prompt overall — make it clearer, more specific, and more effective.',
                    'concise'      => 'Shorten the prompt — remove repetition and make it more concise while keeping the essentials.',
                    'detailed'     => 'Expand the prompt — add more details and specific guidelines.',
                    'friendly'     => 'Make the prompt friendlier — add warmth and humanity.',
                    'professional' => 'Make the prompt more professional — improve formality and precision.',
                );
                $instruction = $improvement_instructions[ $improvement_type ] ?? $improvement_instructions['general'];

                $prompt = "You are an expert at improving System Prompts for chatbots.

Here is an existing System Prompt:
---
{$current_prompt}
---

" . ( $tone_name ? "Tone name: {$tone_name}\n" : '' ) . "
Task: {$instruction}

Requirements:
- Keep the language in English
- Preserve the general structure if it's good
- Don't completely change the character of the prompt
- Return only the improved prompt, no explanations

Provide only the improved System Prompt.";
            } else {
                $improvement_instructions = array(
                    'general'      => 'שפר את הפרומפט באופן כללי - הפוך אותו ליותר ברור, ספציפי ויעיל.',
                    'concise'      => 'קצר את הפרומפט - הסר חזרות והפוך אותו לתמציתי יותר תוך שמירה על העיקר.',
                    'detailed'     => 'הרחב את הפרומפט - הוסף יותר פרטים והנחיות ספציפיות.',
                    'friendly'     => 'הפוך את הפרומפט לידידותי יותר - הוסף חום ואנושיות.',
                    'professional' => 'הפוך את הפרומפט למקצועי יותר - שפר את הרשמיות והדיוק.',
                );
                $instruction = $improvement_instructions[ $improvement_type ] ?? $improvement_instructions['general'];

                $prompt = "אתה מומחה לשיפור הנחיות מערכת (System Prompts) לבוטים.

הנה System Prompt קיים:
---
{$current_prompt}
---

" . ( $tone_name ? "שם הטון: {$tone_name}\n" : '' ) . "
משימה: {$instruction}

דרישות:
- שמור על השפה העברית
- שמור על המבנה הכללי אם הוא טוב
- אל תשנה לחלוטין את האופי של הפרומפט
- החזר רק את הפרומפט המשופר, ללא הסברים

תן רק את ה-System Prompt המשופר.";
            }

            $response = $ai_client->send_message(
                array(
                    array(
                        'role'    => 'user',
                        'content' => $prompt,
                    ),
                ),
                array(
                    'max_tokens'  => 1024,
                    'temperature' => 0.5,
                )
            );

            $improved_prompt = trim( (string) ( $response['content'] ?? '' ) );
            if ( '' === $improved_prompt ) {
                throw new Exception( 'Empty response from AI improvement.' );
            }

            return $this->success( array(
                'system_prompt' => $improved_prompt,
                'message'       => __( 'System prompt improved successfully', 'boostbot' ),
            ) );

        } catch ( Exception $e ) {
            if ( class_exists( 'BoostBot_Logger' ) ) {
                BoostBot_Logger::error( 'Failed to improve tone prompt', array(
                    'error' => $e->getMessage(),
                ) );
            }

            return $this->error( __( 'Failed to improve system prompt: ', 'boostbot' ) . $e->getMessage(), 500 );
        }
    }
}





