<?php
/**
 * Odysseo SEO — Google Gemini provider (generateContent, JSON mime type).
 *
 * @package    Odysseo
 * @author     Chandrabhan Shekhawat
 * @company    Gigai Kripa Services
 * @link       https://gigaikripaservices.com/
 * @copyright  Copyright (c) 2026, Gigai Kripa Services
 */

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

/**
 * Calls the Gemini generateContent API and returns the parsed SEO fields.
 */
class Odysseo_SEO_Provider_Gemini implements Odysseo_SEO_Provider_Interface {

	const BASE = 'https://generativelanguage.googleapis.com/v1beta/models/';

	/**
	 * {@inheritDoc}
	 */
	public function generate( $title, $content, $model, $api_key ) {
		$model = $model ? $model : 'gemini-1.5-flash';
		$url   = self::BASE . rawurlencode( $model ) . ':generateContent?key=' . rawurlencode( $api_key );

		$prompt = odysseo_seo_system_prompt() . "\n\n" . odysseo_seo_build_prompt( $title, $content );

		$body = wp_json_encode(
			array(
				'contents'         => array(
					array( 'parts' => array( array( 'text' => $prompt ) ) ),
				),
				'generationConfig' => array(
					'temperature'      => 0.5,
					'response_mime_type' => 'application/json',
				),
			)
		);

		$response = wp_remote_post(
			$url,
			array(
				'timeout' => 30,
				'headers' => array( 'Content-Type' => 'application/json' ),
				'body'    => $body,
			)
		);

		if ( is_wp_error( $response ) ) {
			return new WP_Error( 'http', $response->get_error_message() );
		}

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

		if ( 200 !== (int) $code ) {
			$msg = isset( $json['error']['message'] ) ? $json['error']['message'] : sprintf( /* translators: %d: HTTP status code. */ __( 'Gemini request failed (HTTP %d).', 'odysseo-core' ), (int) $code );
			return new WP_Error( 'api', $msg );
		}

		$text = isset( $json['candidates'][0]['content']['parts'][0]['text'] ) ? $json['candidates'][0]['content']['parts'][0]['text'] : '';
		if ( '' === $text ) {
			return new WP_Error( 'empty', __( 'Gemini returned no content (it may have been blocked by a safety filter).', 'odysseo-core' ) );
		}
		return odysseo_seo_extract_json( $text );
	}
}
