<?php
/**
 * SEO Analysis competitor controller.
 *
 * @package SmartyPress_AI_Engine
 */

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

/**
 * REST controller for competitor research.
 */
class SmartyPress_AI_SEO_Analysis_Competitor_Controller {

	/**
	 * AI providers.
	 *
	 * @var array
	 */
	private $providers;

	/**
	 * Plugin settings.
	 *
	 * @var array
	 */
	private $settings;

	/**
	 * Capability helper.
	 *
	 * @var SmartyPress_AI_SEO_Analysis_OpenRouter_Capabilities
	 */
	private $capabilities;

	/**
	 * Research service.
	 *
	 * @var SmartyPress_AI_SEO_Analysis_Competitor_Research_Service
	 */
	private $service;

	/**
	 * Constructor.
	 *
	 * @param array                                                 $providers    AI providers.
	 * @param array                                                 $settings     Plugin settings.
	 * @param SmartyPress_AI_SEO_Analysis_OpenRouter_Capabilities     $capabilities Capability helper.
	 * @param SmartyPress_AI_SEO_Analysis_Competitor_Research_Service $service      Research service.
	 */
	public function __construct( array $providers, array $settings, SmartyPress_AI_SEO_Analysis_OpenRouter_Capabilities $capabilities, SmartyPress_AI_SEO_Analysis_Competitor_Research_Service $service ) {
		$this->providers    = $providers;
		$this->settings     = $settings;
		$this->capabilities = $capabilities;
		$this->service      = $service;
	}

	/**
	 * Register REST route.
	 *
	 * @return void
	 */
	public function register_routes() {
		register_rest_route(
			'smartypress/v1',
			'/seo-analysis/competitors',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'search_competitors_endpoint' ),
				'permission_callback' => array( $this, 'check_permissions' ),
			)
		);
	}

	/**
	 * Check REST permissions.
	 *
	 * @return bool
	 */
	public function check_permissions() {
		return current_user_can( 'edit_posts' );
	}

	/**
	 * Search competitors by focus keyword through an OpenRouter Sonar model.
	 *
	 * @param WP_REST_Request $request REST request.
	 * @return WP_REST_Response
	 */
	public function search_competitors_endpoint( $request ) {
		$keyword = sanitize_text_field( $request->get_param( 'keyword' ) );
		$provider_name = sanitize_key( $request->get_param( 'provider' ) );
		$model = sanitize_text_field( $request->get_param( 'model' ) );
		$language = sanitize_text_field( $request->get_param( 'language' ) );
		$limit = min( 10, max( 1, absint( $request->get_param( 'limit' ) ?: 10 ) ) );
		$analysis_limit = min( 10, max( 1, absint( $request->get_param( 'analysisLimit' ) ?: min( 5, $limit ) ) ) );

		$validation_error = $this->validate_request( $keyword, $provider_name, $model );
		if ( $validation_error ) {
			return rest_ensure_response( $validation_error );
		}

		$provider = $this->providers['openrouter'] ?? null;
		if ( ! $provider ) {
			return rest_ensure_response(
				array(
					'success'    => false,
					'error'      => __( 'OpenRouter provider is not available.', 'smartypress-ai-engine' ),
					'error_code' => 'provider_unavailable',
				)
			);
		}

		$result = $this->service->research( $provider, $model, $keyword, $language, $limit, $analysis_limit );
		$this->log_competitor_search_event( $provider_name, $model, $keyword, count( $result['competitors'] ?? array() ), empty( $result['success'] ) ? ( $result['error_code'] ?? 'provider_error' ) : '' );

		if ( empty( $result['success'] ) ) {
			return rest_ensure_response( $result );
		}

		return rest_ensure_response(
			array(
				'success'       => true,
				'keyword'       => $keyword,
				'provider'      => $provider_name,
				'model'         => $model,
				'competitors'   => $result['competitors'],
				'analysisLimit' => $analysis_limit,
			)
		);
	}

	/**
	 * Validate competitor research request.
	 *
	 * @param string $keyword       Focus keyword.
	 * @param string $provider_name Provider name.
	 * @param string $model         Model ID.
	 * @return array|null
	 */
	private function validate_request( $keyword, $provider_name, $model ) {
		if ( '' === $keyword ) {
			return array(
				'success'    => false,
				'error'      => __( 'Focus keyword is required.', 'smartypress-ai-engine' ),
				'error_code' => 'keyword_required',
			);
		}

		if ( 'openrouter' !== $provider_name ) {
			return array(
				'success'    => false,
				'error'      => __( 'Competitor research MVP supports only OpenRouter Sonar models.', 'smartypress-ai-engine' ),
				'error_code' => 'unsupported_provider',
			);
		}

		if ( ! $this->capabilities->is_openrouter_sonar_model( $model ) || ! SmartyPress_AI_Model_Map::supports( 'openrouter', $model, 'web_search' ) ) {
			return array(
				'success'    => false,
				'error'      => __( 'Select an OpenRouter Sonar model for competitor research.', 'smartypress-ai-engine' ),
				'error_code' => 'unsupported_model',
			);
		}

		if ( empty( $this->settings['openrouter_api_key'] ) ) {
			return array(
				'success'    => false,
				'error'      => __( 'OpenRouter API key is not configured.', 'smartypress-ai-engine' ),
				'error_code' => 'api_key_missing',
			);
		}

		if ( ! $this->is_openrouter_model_enabled( $model ) ) {
			return array(
				'success'    => false,
				'error'      => __( 'Selected Sonar model is not enabled in OpenRouter settings.', 'smartypress-ai-engine' ),
				'error_code' => 'model_not_enabled',
			);
		}

		return null;
	}

	/**
	 * Check if an OpenRouter model is enabled by settings.
	 *
	 * @param string $model Model ID.
	 * @return bool
	 */
	private function is_openrouter_model_enabled( $model ) {
		$enabled = $this->settings['openrouter_enabled_text_models'] ?? array();

		if ( empty( $enabled ) ) {
			return true;
		}

		return is_array( $enabled ) && in_array( $model, $enabled, true );
	}

	/**
	 * Log competitor search diagnostics without full AI output.
	 *
	 * @param string $provider_name Provider name.
	 * @param string $model         Model ID.
	 * @param string $keyword       Focus keyword.
	 * @param int    $result_count  Result count.
	 * @param string $error_code    Error code.
	 * @return void
	 */
	private function log_competitor_search_event( $provider_name, $model, $keyword, $result_count, $error_code = '' ) {
		if ( ! class_exists( 'SmartyPress_AI_Logger' ) ) {
			return;
		}

		SmartyPress_AI_Logger::log_module_event(
			'seo_analysis',
			'' === $error_code ? 'competitor_search_completed' : 'competitor_search_failed',
			array(
				'provider'     => sanitize_key( $provider_name ),
				'model'        => sanitize_text_field( $model ),
				'keyword'      => sanitize_text_field( $keyword ),
				'result_count' => absint( $result_count ),
				'error_code'   => sanitize_key( $error_code ),
			),
			'' === $error_code
		);
	}
}
