<?php
/**
 * AI Instruction Optimization for Replyan AI.
 *
 * Analyzes agent instructions and returns an optimized version
 * using the agent's configured AI model.
 *
 * @package Replyan_AI
 */

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

final class Replyan_AI_Optimization_Instruction {

	private const OPTIMIZATION_PROMPT = <<<'PROMPT'
You are an expert AI prompt engineer. Your task is to optimize the following agent instruction text.

Analyze and fix these specific issues:
1. **Redundancy/Duplicates**: Remove repeated rules, overlapping sentences, and duplicate instructions that say the same thing in different ways.
2. **Inconsistent Fallbacks**: Normalize conflicting fallback behaviors. If the instruction says "do X" in one place and "do Y" (contradicting X) in another, unify them into a single clear directive.
3. **HTML Entities**: Strip all HTML entities (e.g., &amp; &lt; &gt; &nbsp; &quot; &#39;) and replace them with their plain text equivalents. The output must contain ONLY plain text, no HTML tags or entities.

Additional guidelines:
- Preserve the original intent, meaning, and personality of the instructions.
- Maintain the same language used in the original (e.g., if written in Tagalog, keep it in Tagalog).
- Improve structure and readability where possible (use clear sections, numbered lists, or bullet points).
- Do NOT add new instructions that were not in the original.
- Do NOT add commentary, explanations, or notes about what you changed.
- Return ONLY the optimized instruction text, nothing else.
PROMPT;

	public function register_hooks(): void {
		add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) );
	}

	public function register_rest_routes(): void {
		register_rest_route( 'replyan/v1', '/admin/optimize-instruction', array(
			'methods'             => WP_REST_Server::CREATABLE,
			'callback'            => array( $this, 'handle_optimize' ),
			'permission_callback' => function () {
				return current_user_can( 'manage_options' );
			},
		) );
	}

	/**
	 * Handle the optimization request.
	 *
	 * @param WP_REST_Request $request The REST request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function handle_optimize( WP_REST_Request $request ) {
		// Increase PHP script timeout if allowed.
		if ( function_exists( 'set_time_limit' ) ) {
			// phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.runtime_configuration_set_time_limit
			@set_time_limit( 120 );
		}

		$instruction = sanitize_textarea_field( wp_unslash( $request->get_param( 'instruction' ) ?? '' ) );
		$agent_id    = absint( $request->get_param( 'agent_id' ) ?? 0 );
		$model_param = sanitize_text_field( wp_unslash( $request->get_param( 'model' ) ?? '' ) );

		if ( '' === trim( $instruction ) ) {
			return new WP_Error(
				'empty_instruction',
				__( 'Instruction text cannot be empty.', 'replyan-ai' ),
				array( 'status' => 400 )
			);
		}

		$settings = Replyan_AI_Settings::get();

		// Override settings for optimization task
		$settings['skip_agent_prompt'] = true;
		$settings['temperature']       = 0.3;
		$settings['max_tokens']        = max( 4000, absint( $settings['max_tokens'] ?? 0 ) );
		$settings['timeout']           = 120;

		if ( ! empty( $model_param ) ) {
			$settings['model'] = $model_param;
			// If model is explicitly passed from active UI tab, avoid overwriting it with DB values
			$settings['skip_agent_fetch'] = true;
		}

		// Ensure system prompt is pristine and not altered by intent or context awareness filters
		$prompt_override_filter = static function () {
			return self::OPTIMIZATION_PROMPT;
		};

		// Ensure WordPress HTTP client allows up to 120s timeout
		$timeout_override_filter = static function () {
			return 120;
		};

		add_filter( 'replyan_ai_system_prompt', $prompt_override_filter, 9999 );
		add_filter( 'http_request_timeout', $timeout_override_filter, 9999 );

		$ajax = new Replyan_AI_Ajax();
		try {
			$response = $ajax->send_to_provider( $settings, $instruction, array(), '', $agent_id );
		} finally {
			remove_filter( 'replyan_ai_system_prompt', $prompt_override_filter, 9999 );
			remove_filter( 'http_request_timeout', $timeout_override_filter, 9999 );
		}

		if ( is_wp_error( $response ) ) {
			return new WP_Error(
				'request_failed',
				$response->get_error_message(),
				array( 'status' => 504 )
			);
		}

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

		if ( $status_code < 200 || $status_code > 299 ) {
			$error_message = $body['error']['message'] ?? __( 'The AI service returned an error.', 'replyan-ai' );
			return new WP_Error( 'api_error', sanitize_text_field( $error_message ), array( 'status' => $status_code ) );
		}

		// Parse response across all provider formats
		$optimized = '';
		if ( isset( $body['choices'][0]['message']['content'] ) ) {
			$optimized = $body['choices'][0]['message']['content'];
		} elseif ( isset( $body['content'][0]['text'] ) ) {
			$optimized = $body['content'][0]['text'];
		} elseif ( isset( $body['candidates'][0]['content']['parts'][0]['text'] ) ) {
			$optimized = $body['candidates'][0]['content']['parts'][0]['text'];
		}

		if ( '' === trim( $optimized ) ) {
			return new WP_Error(
				'empty_optimization',
				__( 'The AI returned an empty optimization result.', 'replyan-ai' ),
				array( 'status' => 500 )
			);
		}

		return rest_ensure_response( array(
			'success' => true,
			'data'    => array(
				'optimized' => $optimized,
			),
		) );
	}
}
