<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Google Provider (Gemini)
 *
 * Implements the AI Platformvider Interface for Google Gemini.
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/includes/api/providers
 */
class Kitsune_AI_Platform_Google_Provider implements Kitsune_AI_Platform_Provider_Interface {

    private $api_key;
    private $api_url = 'https://generativelanguage.googleapis.com/v1beta/models/';

    public function __construct($api_key) {
        $this->api_key = $api_key;
    }

    public function chat($params) {
        $model = $params['model'] ?? KITSUNE_AI_PLATFORM_GOOGLE_GEMINI25_MODELS[0];
        $endpoint = $this->api_url . $model . ':generateContent';
        $timeout = max(1, (int) apply_filters('kitsune_ai_platform_api_timeout', 60, 'google'));

        // Convert messages to Gemini format
        $contents = array();
        foreach ($params['messages'] as $msg) {
            $role = ($msg['role'] === 'user') ? 'user' : 'model';
            // System prompts for Gemini are handled differently or just prepended as user/model
            if ($msg['role'] === 'system') {
                $role = 'user'; // Treat system as user instruction for basic compatibility
            }
            
            $contents[] = array(
                'role' => $role,
                'parts' => array(
                    array('text' => $msg['content'])
                )
            );
        }

        $generationConfig = array();
        if (in_array($model, KITSUNE_AI_PLATFORM_GOOGLE_GEMINI3_MODELS, true)) {
            foreach (KITSUNE_AI_PLATFORM_GOOGLE_GEMINI3_OPTIONS as $option) {
                $key = $option['key'];
                if (isset($params[$key])) {
                    if ($key === 'thinking_level') {
                        $generationConfig['thinkingConfig'] = array(
                            'thinkingLevel' => sanitize_text_field((string) $params[$key]),
                        );
                        continue;
                    }

                    $generationConfig[$key] = $params[$key];
                }
            }
        } elseif (in_array($model, KITSUNE_AI_PLATFORM_GOOGLE_GEMINI25_MODELS, true)) {
            foreach (KITSUNE_AI_PLATFORM_GOOGLE_GEMINI25_OPTIONS as $option) {
                $key = $option['key'];
                if (isset($params[$key])) {
                    $generationConfig[$key] = $params[$key];
                }
            }
        }

        $body = array(
            'contents' => $contents,
        );
        if (!empty($generationConfig)) {
            $body['generationConfig'] = $generationConfig;
        }

        $response = wp_remote_post($endpoint, array(
            'headers' => array(
                'Content-Type' => 'application/json',
                'x-goog-api-key' => $this->api_key, // Secure header usage
            ),
            'body'    => wp_json_encode($body),
            'timeout' => $timeout,
        ));

        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => $response->get_error_message(),
            );
        }

        $code = wp_remote_retrieve_response_code($response);
        $body_response = json_decode(wp_remote_retrieve_body($response), true);

        if ($code !== 200) {
            return array(
                'success' => false,
                'message' => $body_response['error']['message'] ?? __('Google API Error', 'kitsune-ai-platform'),
            );
        }

        $content = $body_response['candidates'][0]['content']['parts'][0]['text'] ?? '';

        return array(
            'success' => true,
            'data'    => array(
                'content' => $content,
                'usage'   => array(), // Gemini doesn't always return token usage in this endpoint format
            ),
        );
    }

    public function validate_key($api_key) {
        $timeout = max(1, (int) apply_filters('kitsune_ai_platform_api_timeout', 60, 'google'));
        
        $response = wp_remote_get('https://generativelanguage.googleapis.com/v1beta/models', array(
            'headers' => array(
                'x-goog-api-key' => $api_key,
            ),
            'timeout' => $timeout,
        ));

        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => $response->get_error_message(),
            );
        }

        $code = wp_remote_retrieve_response_code($response);
        $body_response = json_decode(wp_remote_retrieve_body($response), true);

        if ($code === 200) {
            return array(
                'success' => true,
                'message' => __('Connected successfully to Google Gemini', 'kitsune-ai-platform'),
            );
        }

        $error_msg = $body_response['error']['message'] ?? __('Invalid API Key', 'kitsune-ai-platform');

        return array(
            'success' => false,
            'message' => $error_msg,
        );
    }

    public function embed($params) {
        $model = $params['model'] ?? 'gemini-embedding-001';
        $endpoint = $this->api_url . $model . ':embedContent';
        $timeout = max(1, (int) apply_filters('kitsune_ai_platform_api_timeout', 60, 'google'));

        $input = $params['input'] ?? '';
        if (!is_string($input) || $input === '') {
            return array(
                'success' => false,
                'message' => __('Embedding input is required.', 'kitsune-ai-platform'),
            );
        }

        $body = array(
            'content' => array(
                'parts' => array(
                    array('text' => $input),
                ),
            ),
        );

        $response = wp_remote_post($endpoint, array(
            'headers' => array(
                'Content-Type' => 'application/json',
                'x-goog-api-key' => $this->api_key,
            ),
            'body' => wp_json_encode($body),
            'timeout' => $timeout,
        ));

        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => $response->get_error_message(),
            );
        }

        $code = wp_remote_retrieve_response_code($response);
        $body_response = json_decode(wp_remote_retrieve_body($response), true);

        if ($code !== 200) {
            return array(
                'success' => false,
                'message' => $body_response['error']['message'] ?? __('Google embedding API error', 'kitsune-ai-platform'),
            );
        }

        $vector = $body_response['embedding']['values'] ?? null;
        if (!is_array($vector) || empty($vector)) {
            return array(
                'success' => false,
                'message' => __('Google embedding response missing vector.', 'kitsune-ai-platform'),
            );
        }

        return array(
            'success' => true,
            'data' => array(
                'embedding' => $vector,
                'usage' => array(),
            ),
        );
    }

    public function generate_image($prompt, $params) {
        $model   = sanitize_text_field($params['model'] ?? 'imagen-3.0-generate-001');
        $aspect  = sanitize_text_field($params['aspect_ratio'] ?? '1:1');
        $timeout = max(1, (int) apply_filters('kitsune_ai_platform_api_timeout', 120, 'google'));

        // Imagen supports: 1:1, 3:4, 4:3, 9:16, 16:9
        $allowed_aspects = array('1:1', '3:4', '4:3', '9:16', '16:9');
        if (!in_array($aspect, $allowed_aspects, true)) {
            $aspect = '1:1';
        }

        $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/' . rawurlencode($model) . ':predict';

        $body = array(
            'instances'  => array(
                array('prompt' => $prompt),
            ),
            'parameters' => array(
                'sampleCount' => 1,
                'aspectRatio' => $aspect,
            ),
        );

        $response = wp_remote_post($endpoint, array(
            'headers' => array(
                'Content-Type'   => 'application/json',
                'x-goog-api-key' => $this->api_key,
            ),
            'body'    => wp_json_encode($body),
            'timeout' => $timeout,
        ));

        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => $response->get_error_message(),
            );
        }

        $code          = wp_remote_retrieve_response_code($response);
        $body_response = json_decode(wp_remote_retrieve_body($response), true);

        if ($code !== 200) {
            return array(
                'success' => false,
                'message' => $body_response['error']['message'] ?? __('Google Imagen API error', 'kitsune-ai-platform'),
            );
        }

        $b64   = $body_response['predictions'][0]['bytesBase64Encoded'] ?? '';
        $mime  = $body_response['predictions'][0]['mimeType'] ?? 'image/png';

        if ($b64 === '') {
            return array(
                'success' => false,
                'message' => __('Google Imagen returned no image data.', 'kitsune-ai-platform'),
            );
        }

        // Save base64 image to WP uploads and return the URL
        $ext        = ($mime === 'image/jpeg') ? 'jpg' : 'png';
        $filename   = 'ai-imagen-' . uniqid() . '.' . $ext;
        $upload_dir = wp_upload_dir();
        $file_path  = trailingslashit($upload_dir['path']) . $filename;
        $file_url   = trailingslashit($upload_dir['url']) . $filename;

        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
        $written = file_put_contents($file_path, base64_decode($b64));

        if ($written === false) {
            return array(
                'success' => false,
                'message' => __('Failed to save generated image to uploads.', 'kitsune-ai-platform'),
            );
        }

        return array(
            'success' => true,
            'data'    => array(
                'url'      => esc_url_raw($file_url),
                'model'    => $model,
                'provider' => 'google',
            ),
        );
    }
}
