<?php
/**
 * Odysseo SEO — OpenAI provider (Chat Completions, JSON mode).
 *
 * @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 OpenAI Chat Completions API and returns the parsed SEO fields.
 */
class Odysseo_SEO_Provider_OpenAI implements Odysseo_SEO_Provider_Interface {

	const ENDPOINT = 'https://api.openai.com/v1/chat/completions';

	/**
	 * {@inheritDoc}
	 */
	public function generate( $title, $content, $model, $api_key ) {
		$body = wp_json_encode(
			array(
				'model'           => $model ? $model : 'gpt-4o-mini',
				'temperature'     => 0.5,
				'response_format' => array( 'type' => 'json_object' ),
				'messages'        => array(
					array( 'role' => 'system', 'content' => odysseo_seo_system_prompt() ),
					array( 'role' => 'user',   'content' => odysseo_seo_build_prompt( $title, $content ) ),
				),
			)
		);

		$response = wp_remote_post(
			self::ENDPOINT,
			array(
				'timeout' => 30,
				'headers' => array(
					'Authorization' => 'Bearer ' . $api_key,
					'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. */ __( 'OpenAI request failed (HTTP %d).', 'odysseo-core' ), (int) $code );
			return new WP_Error( 'api', $msg );
		}

		$text = isset( $json['choices'][0]['message']['content'] ) ? $json['choices'][0]['message']['content'] : '';
		return odysseo_seo_extract_json( $text );
	}
}
