<?php
/**
 * AI Provider - Handles API calls to OpenAI, Google Gemini, and Groq
 *
 * @package ContentReply_AI
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class WPSC_AI_Provider {

    private $api_key;
    private $provider;
    private $model;
    private $max_tokens;

    public function __construct() {
        $this->api_key    = get_option( 'wpsc_api_key', '' );
        $this->provider   = get_option( 'wpsc_ai_provider', 'openai' );
        $this->model      = get_option( 'wpsc_ai_model', 'gpt-4o-mini' );
        $this->max_tokens = (int) get_option( 'wpsc_max_tokens', 500 );
    }

    /**
     * Check if API key is configured
     */
    public function is_configured() {
        return ! empty( $this->api_key );
    }

    /**
     * Generate a chat response
     */
    public function get_response( $user_message, $context_chunks = array() ) {
        if ( ! $this->is_configured() ) {
            return array(
                'success' => false,
                'message' => 'AI provider is not configured. Please add your API key in settings.',
            );
        }

        // Build context from indexed content
        $context = $this->build_context( $context_chunks );

        // Build system prompt
        $site_name = get_bloginfo( 'name' );
        $bot_name = get_option( 'wpsc_bot_name', 'Support Bot' );
        $fallback_message = get_option( 'wpsc_fallback_message' );

        $system_prompt = "You are {$bot_name}, a helpful support assistant for {$site_name}. "
            . "Answer questions based ONLY on the following website content. "
            . "Be concise, friendly, and helpful. "
            . "If the answer is not in the provided content, say: \"{$fallback_message}\" "
            . "Do not make up information. "
            . "If relevant, mention the page where the user can find more details.\n\n"
            . "WEBSITE CONTENT:\n{$context}";

        // Route to the correct provider
        if ( $this->provider === 'gemini' ) {
            return $this->call_gemini( $system_prompt, $user_message );
        }

        if ( $this->provider === 'groq' ) {
            return $this->call_groq( $system_prompt, $user_message );
        }

        return $this->call_openai( $system_prompt, $user_message );
    }

    /**
     * Call OpenAI Chat Completions API
     */
    private function call_openai( $system_prompt, $user_message ) {
        $url = 'https://api.openai.com/v1/chat/completions';

        $body = array(
            'model'      => $this->model,
            'messages'   => array(
                array( 'role' => 'system', 'content' => $system_prompt ),
                array( 'role' => 'user', 'content' => $user_message ),
            ),
            'max_tokens'  => $this->max_tokens,
            'temperature' => 0.3,
        );

        $args = array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type'  => 'application/json',
            ),
            'body'    => wp_json_encode( $body ),
            'timeout' => 30,
        );

        $response = wp_remote_post( $url, $args );

        if ( is_wp_error( $response ) ) {
            return array(
                'success' => false,
                'message' => 'Connection error. Please try again.',
            );
        }

        $status_code = wp_remote_retrieve_response_code( $response );
        $body = json_decode( wp_remote_retrieve_body( $response ), true );

        if ( $status_code !== 200 ) {
            $error_msg = isset( $body['error']['message'] ) ? $body['error']['message'] : 'API error occurred.';
            return array(
                'success' => false,
                'message' => $error_msg,
            );
        }

        $ai_response = isset( $body['choices'][0]['message']['content'] )
            ? trim( $body['choices'][0]['message']['content'] )
            : 'Sorry, I could not generate a response.';

        return array(
            'success' => true,
            'message' => $ai_response,
        );
    }

    /**
     * Call Google Gemini API
     */
    private function call_gemini( $system_prompt, $user_message ) {
        $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $this->model . ':generateContent?key=' . $this->api_key;

        $body = array(
            'system_instruction' => array(
                'parts' => array(
                    array( 'text' => $system_prompt ),
                ),
            ),
            'contents' => array(
                array(
                    'parts' => array(
                        array( 'text' => $user_message ),
                    ),
                ),
            ),
            'generationConfig' => array(
                'temperature'     => 0.3,
                'maxOutputTokens' => $this->max_tokens,
            ),
        );

        $args = array(
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'body'    => wp_json_encode( $body ),
            'timeout' => 30,
        );

        $response = wp_remote_post( $url, $args );

        if ( is_wp_error( $response ) ) {
            return array(
                'success' => false,
                'message' => 'Connection error. Please try again.',
            );
        }

        $status_code = wp_remote_retrieve_response_code( $response );
        $body = json_decode( wp_remote_retrieve_body( $response ), true );

        if ( $status_code !== 200 ) {
            $error_msg = isset( $body['error']['message'] ) ? $body['error']['message'] : 'Gemini API error occurred.';
            return array(
                'success' => false,
                'message' => $error_msg,
            );
        }

        // Extract response text from Gemini format
        $ai_response = '';
        if ( isset( $body['candidates'][0]['content']['parts'][0]['text'] ) ) {
            $ai_response = trim( $body['candidates'][0]['content']['parts'][0]['text'] );
        }

        if ( empty( $ai_response ) ) {
            return array(
                'success' => false,
                'message' => 'Sorry, I could not generate a response.',
            );
        }

        return array(
            'success' => true,
            'message' => $ai_response,
        );
    }

    /**
     * Call Groq API (OpenAI-compatible format)
     */
    private function call_groq( $system_prompt, $user_message ) {
        $url = 'https://api.groq.com/openai/v1/chat/completions';

        $body = array(
            'model'      => $this->model,
            'messages'   => array(
                array( 'role' => 'system', 'content' => $system_prompt ),
                array( 'role' => 'user', 'content' => $user_message ),
            ),
            'max_tokens'  => $this->max_tokens,
            'temperature' => 0.3,
        );

        $args = array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type'  => 'application/json',
            ),
            'body'    => wp_json_encode( $body ),
            'timeout' => 30,
        );

        $response = wp_remote_post( $url, $args );

        if ( is_wp_error( $response ) ) {
            return array(
                'success' => false,
                'message' => 'Connection error. Please try again.',
            );
        }

        $status_code = wp_remote_retrieve_response_code( $response );
        $body = json_decode( wp_remote_retrieve_body( $response ), true );

        if ( $status_code !== 200 ) {
            $error_msg = isset( $body['error']['message'] ) ? $body['error']['message'] : 'Groq API error occurred.';
            return array(
                'success' => false,
                'message' => $error_msg,
            );
        }

        $ai_response = isset( $body['choices'][0]['message']['content'] )
            ? trim( $body['choices'][0]['message']['content'] )
            : 'Sorry, I could not generate a response.';

        return array(
            'success' => true,
            'message' => $ai_response,
        );
    }

    /**
     * Build context string from content chunks
     */
    private function build_context( $chunks ) {
        if ( empty( $chunks ) ) {
            return 'No relevant content found.';
        }

        $context_parts = array();
        foreach ( $chunks as $chunk ) {
            $context_parts[] = "[Page: {$chunk->post_title}]\n{$chunk->chunk_content}\nURL: {$chunk->post_url}";
        }

        return implode( "\n\n---\n\n", $context_parts );
    }
}
