<?php
/**
 * Widget Analyzer Endpoint for BoostBot REST API.
 *
 * Uses Gemini Flash to analyze conversation and recommend widgets.
 * Called after the bot response completes for intelligent widget detection.
 *
 * @package BoostBot
 * @since 1.16.0
 */

// Prevent direct access to the file.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * BoostBot_Widget_Analyzer_Endpoint class.
 *
 * Provides AI-powered widget recommendation after bot responses.
 *
 * @since 1.16.0
 */
class BoostBot_Widget_Analyzer_Endpoint extends BoostBot_Base_Endpoint {

    /**
     * The base path for this endpoint.
     *
     * @since 1.16.0
     * @access protected
     * @var string $rest_base
     */
    protected $rest_base = 'chat';

    /**
     * Register the routes for this endpoint.
     *
     * @since 1.16.0
     */
    public function register() {
        // POST /wp-json/boostbot/v1/chat/analyze-widget
        $this->register_route(
            '/analyze-widget',
            'POST',
            array( $this, 'analyze_widget' ),
            array( $this, 'public_with_rate_limit' ),
            $this->get_analyze_args()
        );
    }

    /**
     * Analyze conversation and recommend widget using Gemini Flash.
     *
     * @since 1.16.0
     * @param WP_REST_Request $request The REST request object.
     * @return WP_REST_Response|WP_Error The response or error.
     */
    public function analyze_widget( $request ) {
        BoostBot_Logger::warning( '[Deprecated] FLOW=DIRECT_WIDGET_ANALYZER endpoint /chat/analyze-widget was called. Canonical flow uses Gemini orchestrator widget decisions.' );
        $t0 = microtime( true );
        
        $user_message = sanitize_textarea_field( $request->get_param( 'user_message' ) );
        $bot_response = sanitize_textarea_field( $request->get_param( 'bot_response' ) );
        $history = $request->get_param( 'history' ) ?: array();
        $visitor_id = sanitize_text_field( $request->get_param( 'visitor_id' ) );

        if ( empty( $user_message ) || empty( $bot_response ) ) {
            return $this->error( __( 'user_message and bot_response are required', 'boostbot' ), 400 );
        }

        try {
            // Get bot's widget types (NEVER use global settings - each bot has its own widgets)
            $bot_id = absint( $request->get_param( 'bot_id' ) );
            $widgets_enabled = $this->get_bot_widget_types( $bot_id );
            
            // If bot has no widgets assigned, skip analysis
            if ( empty( $widgets_enabled ) ) {
                BoostBot_Logger::info( sprintf( '[DEBUG] Widget analyzer: Bot %d has no widgets assigned, skipping', $bot_id ) );
                return $this->success( array(
                    'widget'    => null,
                    'timing_ms' => round( ( microtime( true ) - $t0 ) * 1000 ),
                ) );
            }
            
            // Build the analysis prompt
            $analysis_prompt = $this->build_analysis_prompt( $user_message, $bot_response, $history, $widgets_enabled );
            
            // Call Gemini Flash via backend
            $widget_recommendation = $this->call_gemini_flash( $analysis_prompt );
            
            $elapsed_ms = round( ( microtime( true ) - $t0 ) * 1000 );
            BoostBot_Logger::info( sprintf( '[TIMING] analyze_widget.total: %dms', $elapsed_ms ) );
            
            if ( empty( $widget_recommendation ) || $widget_recommendation === 'none' ) {
                BoostBot_Logger::info( '[DEBUG] Widget analyzer: no widget recommended' );
                return $this->success( array(
                    'widget'    => null,
                    'timing_ms' => $elapsed_ms,
                ) );
            }
            
            // Parse and return widget config
            $widget_config = $this->get_widget_config( $widget_recommendation );
            
            if ( $widget_config ) {
                BoostBot_Logger::info( sprintf( '[DEBUG] Widget analyzer recommended: %s', $widget_recommendation ) );
            }
            
            return $this->success( array(
                'widget'    => $widget_config,
                'timing_ms' => $elapsed_ms,
            ) );

        } catch ( Exception $e ) {
            BoostBot_Logger::error( 'Widget analyzer error: ' . $e->getMessage() );
            return $this->success( array(
                'widget'    => null,
                'error'     => $e->getMessage(),
                'timing_ms' => round( ( microtime( true ) - $t0 ) * 1000 ),
            ) );
        }
    }

    /**
     * Build the analysis prompt for Gemini Flash.
     *
     * @param string $user_message  User's message.
     * @param string $bot_response  Bot's response.
     * @param array  $history       Conversation history.
     * @param array  $widgets       Available widgets.
     * @return string The analysis prompt.
     */
    private function build_analysis_prompt( string $user_message, string $bot_response, array $history, array $widgets ): string {
        $widget_descriptions = array(
            'form'             => 'Contact form for collecting user details (name, email, phone) - show when user wants to be contacted, leave details, or needs human assistance',
            'lead_form'        => 'Contact form for collecting user details (name, email, phone) - show when user wants to be contacted, leave details, or needs human assistance',
            'calendar_meeting' => 'Meeting/call scheduler - show when user wants to schedule a meeting, appointment, or phone call',
            'calendar_call'    => 'Meeting/call scheduler - show when user wants to schedule a meeting, appointment, or phone call',
            'youtube'          => 'YouTube video player - show when user asks to watch a video, see a clip, or mentions YouTube',
            'gallery'          => 'Image gallery / portfolio - show when user asks to see photos, examples, work samples, or portfolio',
            'whatsapp'         => 'WhatsApp chat link - show when user asks to contact via WhatsApp',
            'contact_card'     => 'Contact card with staff details - show when user asks who to talk to, wants contact info, or asks about team members',
            'survey'           => 'Satisfaction survey - show ONLY at end of conversation when user is satisfied and has no more questions',
        );
        
        $available_widgets = array();
        foreach ( $widgets as $widget ) {
            if ( isset( $widget_descriptions[ $widget ] ) ) {
                $available_widgets[] = "- {$widget}: {$widget_descriptions[$widget]}";
            }
        }
        
        $widgets_list = implode( "\n", $available_widgets );
        
        // Build conversation context
        $conversation = "";
        foreach ( array_slice( $history, -4 ) as $msg ) {
            $role = ( $msg['role'] ?? 'user' ) === 'assistant' ? 'Bot' : 'User';
            $content = $msg['content'] ?? '';
            if ( ! empty( $content ) ) {
                $conversation .= "{$role}: {$content}\n";
            }
        }
        $conversation .= "User: {$user_message}\n";
        $conversation .= "Bot: {$bot_response}\n";
        
        return "Analyze this conversation and decide if a widget should be shown to help the user.\n\n"
            . "AVAILABLE WIDGETS:\n"
            . "{$widgets_list}\n\n"
            . "CONVERSATION:\n"
            . "{$conversation}\n\n"
            . "RULES:\n"
            . "1. Only recommend a widget if it clearly helps the user based on BOTH their request AND the bot's response\n"
            . "2. If the user asks to leave details, fill a form, be contacted, or the bot suggests they should leave details - recommend \"lead_form\"\n"
            . "3. If the user wants to schedule a meeting/appointment - recommend \"calendar_meeting\"\n"
            . "4. If the user wants to schedule a call - recommend \"calendar_call\"\n"
            . "5. If no widget is appropriate - respond with \"none\"\n\n"
            . "Respond with ONLY the widget type name (e.g., \"lead_form\") or \"none\". No explanation.";
    }

    /**
     * Call Gemini Flash for widget analysis.
     *
     * @param string $prompt The analysis prompt.
     * @return string Widget type or 'none'.
     */
    private function call_gemini_flash( string $prompt ): string {
        if ( ! class_exists( 'BoostBot_Credits_Backend_Client' ) ) {
            BoostBot_Logger::error( 'Widget analyzer: Backend client not available' );
            return 'none';
        }
        
        try {
            $client = new BoostBot_Credits_Backend_Client();
            $site_id = $client->ensure_site_id();
            
            if ( is_wp_error( $site_id ) ) {
                BoostBot_Logger::error( 'Widget analyzer: Site ID error - ' . $site_id->get_error_message() );
                return 'none';
            }
            
            // Use a simple chat completion for widget analysis
            // This should use Gemini Flash which is fast and cheap
            $result = $client->quick_llm_call(
                (string) $site_id,
                array(
                    'model'      => 'gemini-2.0-flash',
                    'prompt'     => $prompt,
                    'max_tokens' => 20,
                    'purpose'    => 'widget_analysis',
                )
            );
            
            if ( is_wp_error( $result ) ) {
                BoostBot_Logger::error( 'Widget analyzer: LLM error - ' . $result->get_error_message() );
                return 'none';
            }
            
            // Extract the response text
            $response = $result['response'] ?? $result['text'] ?? $result['content'] ?? '';
            $response = trim( strtolower( $response ) );
            
            // Validate response is a known widget or 'none'
            $valid_widgets = array( 'lead_form', 'calendar_meeting', 'calendar_call', 'none' );
            if ( in_array( $response, $valid_widgets, true ) ) {
                return $response;
            }
            
            // Try to extract widget name from response
            foreach ( $valid_widgets as $widget ) {
                if ( strpos( $response, $widget ) !== false ) {
                    return $widget;
                }
            }
            
            return 'none';
            
        } catch ( Exception $e ) {
            BoostBot_Logger::error( 'Widget analyzer exception: ' . $e->getMessage() );
            return 'none';
        }
    }

    /**
     * Get widget configuration by type.
     *
     * @param string $widget_type Widget type.
     * @return array|null Widget config or null.
     */
    private function get_widget_config( string $widget_type ): ?array {
        switch ( $widget_type ) {
            case 'lead_form':
                // Use Hebrew strings directly (plugin is Hebrew-only for now)
                return array(
                    'type' => 'lead_form',
                    'id'   => 'ai_post_analysis',
                    'data' => array(
                        'title'       => 'השאירו פרטים',
                        'description' => 'נחזור אליכם בהקדם',
                        'fields'      => array(
                            array( 'name' => 'name', 'label' => 'שם', 'type' => 'text', 'required' => true ),
                            array( 'name' => 'email', 'label' => 'אימייל', 'type' => 'email', 'required' => true ),
                            array( 'name' => 'phone', 'label' => 'טלפון', 'type' => 'tel', 'required' => false ),
                            array( 'name' => 'message', 'label' => 'הודעה', 'type' => 'textarea', 'required' => false ),
                        ),
                        'submit_text' => 'שלח',
                    ),
                );
                
            case 'calendar_meeting':
            case 'calendar_call':
                return array(
                    'type' => $widget_type,
                    'id'   => 'ai_post_analysis',
                    'data' => array(
                        'title' => $widget_type === 'calendar_meeting' 
                            ? __( 'Schedule a meeting', 'boostbot' )
                            : __( 'Schedule a call', 'boostbot' ),
                    ),
                );
                
            default:
                return null;
        }
    }

    /**
     * Get argument schema for analyze endpoint.
     *
     * @since 1.16.0
     * @return array Argument schema.
     */
    private function get_analyze_args() {
        return array(
            'user_message' => array(
                'required'          => true,
                'type'              => 'string',
                'sanitize_callback' => 'sanitize_textarea_field',
            ),
            'bot_response' => array(
                'required'          => true,
                'type'              => 'string',
                'sanitize_callback' => 'sanitize_textarea_field',
            ),
            'history' => array(
                'required' => false,
                'type'     => 'array',
            ),
            'visitor_id' => array(
                'required'          => false,
                'type'              => 'string',
                'sanitize_callback' => 'sanitize_text_field',
            ),
            'bot_id' => array(
                'required'          => false,
                'type'              => 'integer',
                'sanitize_callback' => 'absint',
            ),
        );
    }
    
    /**
     * Get widget types assigned to a bot.
     *
     * @param int $bot_id The bot ID.
     * @return array Array of widget type strings.
     */
    private function get_bot_widget_types( int $bot_id ): array {
        if ( $bot_id <= 0 || ! class_exists( 'BoostBot_Widget_Model' ) ) {
            return array();
        }
        
        $widget_types = array();
        try {
            $widget_model = new BoostBot_Widget_Model();
            $assigned_widgets = $widget_model->get_for_chatbot( $bot_id );
            if ( ! empty( $assigned_widgets ) ) {
                foreach ( $assigned_widgets as $widget ) {
                    $widget_type = $widget->type ?? 'unknown';
                    if ( ! in_array( $widget_type, $widget_types, true ) ) {
                        $widget_types[] = $widget_type;
                    }
                }
            }
        } catch ( Exception $e ) {
            BoostBot_Logger::error( 'Widget analyzer: Failed to get bot widgets: ' . $e->getMessage() );
        }
        
        return $widget_types;
    }
}
