<?php

namespace AtlasAiDev\Awfah\REST;

use AtlasAiDev\Awfah\Admin\Editor_Experiments;
use WP_REST_Controller;
use WP_REST_Request;
use WP_REST_Response;

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

/**
 * REST controller for the AI Experiments settings (block-editor experiments).
 *
 * Additive: stores its own option (awfah_experiment_settings) and does not touch
 * any existing settings, keys, or endpoints. Routes: GET/POST awfah/v1/experiments.
 */
class Experiments_Controller extends WP_REST_Controller {

	/**
	 * Option key holding per-experiment settings.
	 */
	const OPTION_KEY = 'awfah_experiment_settings';

	public function __construct() {
		$this->namespace = 'awfah/v1';
		$this->rest_base = 'experiments';
	}

	/**
	 * The five block-editor experiments, keyed by tool slug.
	 *
	 * @return array<string, array{label:string, description:string}>
	 */
	public static function experiments(): array {
		return array(
			'generate-excerpt'    => array(
				'label'       => __( 'Excerpt generation', 'ai-workflow-automation-ai-agent-hub' ),
				'description' => __( 'Post sidebar excerpt panel', 'ai-workflow-automation-ai-agent-hub' ),
			),
			'image-generation'    => array(
				'label'       => __( 'Feature image generation', 'ai-workflow-automation-ai-agent-hub' ),
				'description' => __( 'Featured image panel', 'ai-workflow-automation-ai-agent-hub' ),
			),
			'summarization'       => array(
				'label'       => __( 'Summarization', 'ai-workflow-automation-ai-agent-hub' ),
				'description' => __( 'Post summary panel', 'ai-workflow-automation-ai-agent-hub' ),
			),
			'suggest-titles'      => array(
				'label'       => __( 'Title suggestions', 'ai-workflow-automation-ai-agent-hub' ),
				'description' => __( 'Editor toolbar', 'ai-workflow-automation-ai-agent-hub' ),
			),
			'alt-text-generation' => array(
				'label'       => __( 'Alt text generation', 'ai-workflow-automation-ai-agent-hub' ),
				'description' => __( 'Image blocks', 'ai-workflow-automation-ai-agent-hub' ),
			),
		);
	}

	/**
	 * Resolved settings for one experiment, merged with defaults.
	 * Consumed by Editor_Experiments when localizing each experiment.
	 *
	 * @param string $key Experiment tool slug.
	 * @return array{enabled:bool, provider:string, prompt:string}
	 */
	public static function get_experiment_settings( string $key ): array {
		$all   = get_option( self::OPTION_KEY, array() );
		$saved = ( is_array( $all ) && isset( $all[ $key ] ) && is_array( $all[ $key ] ) ) ? $all[ $key ] : array();

		return array(
			'enabled'  => isset( $saved['enabled'] ) ? (bool) $saved['enabled'] : true,
			'provider' => ( isset( $saved['provider'] ) && is_string( $saved['provider'] ) && '' !== $saved['provider'] ) ? $saved['provider'] : 'auto',
			'prompt'   => ( isset( $saved['prompt'] ) && is_string( $saved['prompt'] ) ) ? $saved['prompt'] : '',
		);
	}

	public function register_routes(): void {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base,
			array(
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'get_items' ),
					'permission_callback' => array( $this, 'permissions_check' ),
				),
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'save_items' ),
					'permission_callback' => array( $this, 'permissions_check' ),
				),
			)
		);
	}

	public function permissions_check(): bool {
		return current_user_can( 'manage_options' );
	}

	/**
	 * GET — return the experiments with their current settings + built-in default prompt.
	 *
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response
	 */
	public function get_items( $request ): WP_REST_Response {
		$defaults = Editor_Experiments::default_prompts();
		$all      = get_option( self::OPTION_KEY, array() );
		$all      = is_array( $all ) ? $all : array();
		$items    = array();

		foreach ( self::experiments() as $key => $meta ) {
			$settings = self::get_experiment_settings( $key );
			$row      = ( isset( $all[ $key ] ) && is_array( $all[ $key ] ) ) ? $all[ $key ] : array();

			$items[] = array(
				'id'               => $key,
				'label'            => $meta['label'],
				'description'      => $meta['description'],
				'enabled'          => $settings['enabled'],
				'provider'         => $settings['provider'],
				'prompt'           => $settings['prompt'],
				'defaultPrompt'    => isset( $defaults[ $key ] ) ? $defaults[ $key ] : '',
				// Hide the official AI plugin's duplicate of this experiment (AI-10). Default: hide.
				'suppressOfficial' => array_key_exists( 'suppress_official', $row ) ? (bool) $row['suppress_official'] : true,
			);
		}

		return new WP_REST_Response(
			array(
				'experiments'        => $items,
				// Official WordPress AI plugin integration state (AI-10).
				'wpaiActive'         => \AtlasAiDev\Awfah\Integrations\Wpai_Bridge::is_wpai_active(),
				'suppressOfficialAll' => (bool) get_option( \AtlasAiDev\Awfah\Integrations\Wpai_Bridge::SUPPRESS_ALL_OPTION, false ),
			)
		);
	}

	/**
	 * POST — save the experiments settings.
	 *
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response
	 */
	public function save_items( $request ): WP_REST_Response {
		$body     = $request->get_json_params();
		$incoming = ( is_array( $body ) && isset( $body['experiments'] ) && is_array( $body['experiments'] ) ) ? $body['experiments'] : array();
		$valid    = array_keys( self::experiments() );
		$out      = array();

		foreach ( $incoming as $row ) {
			if ( ! is_array( $row ) || empty( $row['id'] ) || ! in_array( $row['id'], $valid, true ) ) {
				continue;
			}

			$out[ $row['id'] ] = array(
				'enabled'           => ! empty( $row['enabled'] ),
				'provider'          => isset( $row['provider'] ) ? sanitize_text_field( (string) $row['provider'] ) : 'auto',
				'prompt'            => isset( $row['prompt'] ) ? sanitize_textarea_field( (string) $row['prompt'] ) : '',
				// Hide the official AI plugin's duplicate of this experiment (AI-10). Default: hide.
				'suppress_official' => ! array_key_exists( 'suppressOfficial', $row ) || ! empty( $row['suppressOfficial'] ),
			);
		}

		update_option( self::OPTION_KEY, $out, false );

		// Global "hide all official AI plugin duplicates" switch (AI-10).
		if ( is_array( $body ) && array_key_exists( 'suppressOfficialAll', $body ) ) {
			update_option(
				\AtlasAiDev\Awfah\Integrations\Wpai_Bridge::SUPPRESS_ALL_OPTION,
				! empty( $body['suppressOfficialAll'] ),
				false
			);
		}

		return new WP_REST_Response(
			array(
				'success'     => true,
				'experiments' => $out,
			)
		);
	}
}
