<?php

namespace AtlasAiDev\Awfah\Admin;

use AtlasAiDev\Awfah\Plugin;

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

/**
 * Registers and enqueues block editor experiment scripts (Gutenberg integrations).
 */
class Editor_Experiments {

	/**
	 * Cached default prompts (lazy-loaded to avoid early translation calls).
	 *
	 * @var array<string, string>|null
	 */
	private ?array $default_prompts = null;

	public function __construct() {
		add_action( 'enqueue_block_editor_assets', [ $this, 'enqueue_excerpt_generation' ] );
		add_action( 'enqueue_block_editor_assets', [ $this, 'enqueue_image_generation' ] );
		add_action( 'enqueue_block_editor_assets', [ $this, 'enqueue_summarization' ] );
		add_action( 'enqueue_block_editor_assets', [ $this, 'enqueue_title_generation' ] );
		add_action( 'enqueue_block_editor_assets', [ $this, 'enqueue_alt_text_generation' ] );
		add_action( 'init', [ $this, 'register_meta' ] );
	}

	/**
	 * Get default prompts. Lazy-loaded so __() is only called at runtime
	 * (after init), not during plugin bootstrap.
	 *
	 * @return array<string, string>
	 */
	private function get_default_prompts(): array {
		if ( null === $this->default_prompts ) {
			$this->default_prompts = self::default_prompts();
		}

		return $this->default_prompts;
	}

	/**
	 * Built-in default prompts for each experiment, keyed by tool slug.
	 * Public so the Experiments settings REST controller can expose them.
	 *
	 * @return array<string, string>
	 */
	public static function default_prompts(): array {
		return [
			'generate-excerpt' => __(
				'You are an expert copywriter. Generate a concise, SEO-friendly excerpt for the following content. '
				. 'The excerpt should be 1-2 sentences, 150-160 characters, and capture the essence of the content. '
				. 'Return only the excerpt text with no additional formatting or explanation.',
				'ai-workflow-automation-ai-agent-hub'
			),
			'image-generation' => __(
				'Create a visually compelling featured image that directly represents the article topic and title. '
				. 'The image must clearly relate to the specific subject matter described in the article. '
				. 'Use professional quality, balanced composition, and make it suitable for a blog header.',
				'ai-workflow-automation-ai-agent-hub'
			),
			'summarization' => __(
				'You are an expert content summarizer. Generate a concise, factual, and neutral summary. '
				. 'Use complete sentences. No markdown, bullets, or numbering — plain text only. '
				. 'Provide a high-level overview, not a list of details.',
				'ai-workflow-automation-ai-agent-hub'
			),
			'suggest-titles' => __(
				'You are an expert copywriter. Generate compelling, SEO-friendly blog post titles. '
				. 'Each title should be under 80 characters, distinct in tone and focus, and reflect actual content. '
				. 'No generic clickbait.',
				'ai-workflow-automation-ai-agent-hub'
			),
			'alt-text-generation' => __(
				'You are an accessibility expert. Generate concise, descriptive alt text for screen readers. '
				. 'Under 125 characters. No "Image of" prefix. Plain text only.',
				'ai-workflow-automation-ai-agent-hub'
			),
		];
	}

	/**
	 * Register post meta for prompts and history.
	 */
	public function register_meta(): void {
		$tools = [ 'generate-excerpt', 'image-generation', 'summarization', 'suggest-titles', 'alt-text-generation' ];

		foreach ( $tools as $tool ) {
			// Per-post prompt.
			register_post_meta(
				'',
				"_awfah_prompt_{$tool}",
				[
					'type'          => 'string',
					'single'        => true,
					'show_in_rest'  => true,
					'auth_callback' => static function () {
						return current_user_can( 'edit_posts' );
					},
				]
			);

			// Per-post generation history.
			register_post_meta(
				'',
				"_awfah_history_{$tool}",
				[
					'type'          => 'array',
					'single'        => true,
					'show_in_rest'  => [
						'schema' => [
							'type'  => 'array',
							'items' => [
								'type'       => 'object',
								'properties' => [
									'result'    => [ 'type' => 'string' ],
									'prompt'    => [ 'type' => 'string' ],
									'tone'      => [ 'type' => 'string' ],
									'style'     => [ 'type' => 'string' ],
									'provider'  => [ 'type' => 'string' ],
									'image_id'  => [ 'type' => 'integer' ],
									'image_url' => [ 'type' => 'string' ],
									'timestamp' => [ 'type' => 'string' ],
								],
							],
						],
					],
					'auth_callback' => static function () {
						return current_user_can( 'edit_posts' );
					},
				]
			);
		}

		// AI-generated flag on attachments (for AILabel component).
		register_post_meta(
			'attachment',
			'_ai_generated',
			[
				'type'          => 'integer',
				'single'        => true,
				'show_in_rest'  => true,
				'auth_callback' => static function () {
					return current_user_can( 'upload_files' );
				},
			]
		);
	}

	/**
	 * Enqueue the excerpt generation experiment script in the block editor.
	 */
	public function enqueue_excerpt_generation(): void {
		$settings = Plugin::get_settings();

		// Only if content_steward module is enabled.
		if ( empty( $settings['modules']['content_steward'] ) ) {
			return;
		}

		// When bridged into the official AI plugin, its Settings > AI toggles
		// (global + our feature card) control this experiment (AI-10).
		if ( ! \AtlasAiDev\Awfah\Integrations\Wpai_Bridge::is_experiment_allowed( 'generate-excerpt' ) ) {
			return;
		}

		$screen = get_current_screen();
		if ( ! $screen ) {
			return;
		}

		// Only for post types that support excerpts.
		if ( ! post_type_supports( $screen->post_type, 'excerpt' ) ) {
			return;
		}

		// Exclude attachment post type.
		if ( 'attachment' === $screen->post_type ) {
			return;
		}

		$build_dir  = AWFAH_PLUGIN_DIR . 'assets/js/experiments-build/excerpt-generation/';
		$build_url  = AWFAH_PLUGIN_URL . 'assets/js/experiments-build/excerpt-generation/';
		$asset_file = $build_dir . 'index.asset.php';

		// Check if the build exists.
		if ( ! file_exists( $asset_file ) ) {
			return;
		}

		$asset = require $asset_file;

		wp_enqueue_script(
			'aah-excerpt-generation',
			$build_url . 'index.js',
			$asset['dependencies'] ?? [],
			$asset['version'] ?? AWFAH_VERSION,
			true
		);

		wp_set_script_translations( 'aah-excerpt-generation', 'ai-workflow-automation-ai-agent-hub' );

		wp_localize_script(
			'aah-excerpt-generation',
			'aahExcerptGeneration',
			$this->get_excerpt_config()
		);

		// No custom stylesheet: the excerpt experiment UI is pure
		// @wordpress/components (AI-10 UI doctrine) — wp-components styles,
		// which the block editor already loads, are all it needs.
	}

	/**
	 * Enqueue the image generation experiment script in the block editor.
	 */
	public function enqueue_image_generation(): void {
		$settings = Plugin::get_settings();

		if ( empty( $settings['modules']['content_steward'] ) ) {
			return;
		}

		if ( ! \AtlasAiDev\Awfah\Integrations\Wpai_Bridge::is_experiment_allowed( 'image-generation' ) ) {
			return;
		}

		$screen = get_current_screen();
		if ( ! $screen ) {
			return;
		}

		// Only for post types that support featured images (thumbnails).
		if ( ! post_type_supports( $screen->post_type, 'thumbnail' ) ) {
			return;
		}

		if ( 'attachment' === $screen->post_type ) {
			return;
		}

		$build_dir  = AWFAH_PLUGIN_DIR . 'assets/js/experiments-build/image-generation/';
		$build_url  = AWFAH_PLUGIN_URL . 'assets/js/experiments-build/image-generation/';
		$asset_file = $build_dir . 'index.asset.php';

		if ( ! file_exists( $asset_file ) ) {
			return;
		}

		$asset = require $asset_file;

		wp_enqueue_script(
			'aah-image-generation',
			$build_url . 'index.js',
			$asset['dependencies'] ?? [],
			$asset['version'] ?? AWFAH_VERSION,
			true
		);

		wp_set_script_translations( 'aah-image-generation', 'ai-workflow-automation-ai-agent-hub' );

		wp_localize_script(
			'aah-image-generation',
			'aahImageGeneration',
			$this->get_image_config()
		);

		// No custom stylesheet: the image generation experiment UI is pure
		// @wordpress/components (AI-10 UI doctrine) — wp-components styles,
		// which the block editor already loads, are all it needs.
	}

	/**
	 * Enqueue the summarization experiment script in the block editor.
	 */
	public function enqueue_summarization(): void {
		$settings = Plugin::get_settings();
		if ( empty( $settings['modules']['content_steward'] ) ) {
			return;
		}

		if ( ! \AtlasAiDev\Awfah\Integrations\Wpai_Bridge::is_experiment_allowed( 'summarization' ) ) {
			return;
		}

		$screen = get_current_screen();
		if ( ! $screen || 'attachment' === $screen->post_type ) {
			return;
		}
		if ( ! post_type_supports( $screen->post_type, 'editor' ) ) {
			return;
		}

		$build_dir  = AWFAH_PLUGIN_DIR . 'assets/js/experiments-build/summarization/';
		$build_url  = AWFAH_PLUGIN_URL . 'assets/js/experiments-build/summarization/';
		$asset_file = $build_dir . 'index.asset.php';

		if ( ! file_exists( $asset_file ) ) {
			return;
		}

		$asset = require $asset_file;

		wp_enqueue_script(
			'aah-summarization',
			$build_url . 'index.js',
			$asset['dependencies'] ?? [],
			$asset['version'] ?? AWFAH_VERSION,
			true
		);

		wp_set_script_translations( 'aah-summarization', 'ai-workflow-automation-ai-agent-hub' );

		wp_localize_script(
			'aah-summarization',
			'aahSummarization',
			$this->get_summarization_config()
		);

		// No custom stylesheet: the summarization experiment UI is pure
		// @wordpress/components (AI-10 UI doctrine) — wp-components styles,
		// which the block editor already loads, are all it needs.
	}

	/**
	 * Enqueue the title generation experiment script in the block editor.
	 */
	public function enqueue_title_generation(): void {
		$settings = Plugin::get_settings();
		if ( empty( $settings['modules']['content_steward'] ) ) {
			return;
		}

		if ( ! \AtlasAiDev\Awfah\Integrations\Wpai_Bridge::is_experiment_allowed( 'suggest-titles' ) ) {
			return;
		}

		$screen = get_current_screen();
		if ( ! $screen || 'attachment' === $screen->post_type ) {
			return;
		}
		if ( ! post_type_supports( $screen->post_type, 'title' ) ) {
			return;
		}

		$build_dir  = AWFAH_PLUGIN_DIR . 'assets/js/experiments-build/title-generation/';
		$build_url  = AWFAH_PLUGIN_URL . 'assets/js/experiments-build/title-generation/';
		$asset_file = $build_dir . 'index.asset.php';

		if ( ! file_exists( $asset_file ) ) {
			return;
		}

		$asset = require $asset_file;

		wp_enqueue_script(
			'aah-title-generation',
			$build_url . 'index.js',
			$asset['dependencies'] ?? [],
			$asset['version'] ?? AWFAH_VERSION,
			true
		);

		wp_set_script_translations( 'aah-title-generation', 'ai-workflow-automation-ai-agent-hub' );

		wp_localize_script(
			'aah-title-generation',
			'aahTitleGeneration',
			$this->get_title_config()
		);

		// No custom stylesheet: the title generation experiment UI is pure
		// @wordpress/components (AI-10 UI doctrine) — wp-components styles,
		// which the block editor already loads, are all it needs.
	}

	/**
	 * Enqueue the alt-text generation experiment script in the block editor.
	 */
	public function enqueue_alt_text_generation(): void {
		$settings = Plugin::get_settings();
		if ( empty( $settings['modules']['content_steward'] ) ) {
			return;
		}

		if ( ! \AtlasAiDev\Awfah\Integrations\Wpai_Bridge::is_experiment_allowed( 'alt-text-generation' ) ) {
			return;
		}

		$build_dir  = AWFAH_PLUGIN_DIR . 'assets/js/experiments-build/alt-text-generation/';
		$build_url  = AWFAH_PLUGIN_URL . 'assets/js/experiments-build/alt-text-generation/';
		$asset_file = $build_dir . 'index.asset.php';

		if ( ! file_exists( $asset_file ) ) {
			return;
		}

		$asset = require $asset_file;

		wp_enqueue_script(
			'aah-alt-text-generation',
			$build_url . 'index.js',
			$asset['dependencies'] ?? [],
			$asset['version'] ?? AWFAH_VERSION,
			true
		);

		wp_set_script_translations( 'aah-alt-text-generation', 'ai-workflow-automation-ai-agent-hub' );

		wp_localize_script(
			'aah-alt-text-generation',
			'aahAltTextGeneration',
			$this->get_alt_text_config()
		);

		// No custom stylesheet: the alt-text generation experiment UI is pure
		// @wordpress/components (AI-10 UI doctrine) — wp-components styles,
		// which the block editor already loads, are all it needs.
	}

	/**
	 * Get the current post ID from the edit screen context.
	 *
	 * @return int Post ID (0 when unknown).
	 */
	protected function get_current_post_id(): int {
		global $post;

		return $post ? (int) $post->ID : 0;
	}

	/**
	 * Localized config for the excerpt generation experiment.
	 *
	 * Shared by the block editor and Classic Editor enqueue paths.
	 *
	 * @return array<string, mixed>
	 */
	protected function get_excerpt_config(): array {
		$default_prompts = $this->get_default_prompts();
		$awfah_exp       = \AtlasAiDev\Awfah\REST\Experiments_Controller::get_experiment_settings( 'generate-excerpt' );

		return [
			'isPro'           => awfah_is_pro_active(),
			'abilitySlug'     => 'awfah-content/generate-excerpt',
			'abilityPath'     => rest_url( 'wp-abilities/v1/abilities/awfah-content/generate-excerpt/run' ),
			'promptsUrl'      => rest_url( 'awfah/v1/prompts/generate-excerpt' ),
			'templatesUrl'    => rest_url( 'awfah/v1/prompts/generate-excerpt/templates' ),
			'explainUrl'      => rest_url( 'awfah/v1/prompts/generate-excerpt/explain' ),
			'providersUrl'    => rest_url( 'awfah/v1/providers' ),
			'modelsUrlBase'   => rest_url( 'awfah/v1/providers' ),
			'wpNonce'         => wp_create_nonce( 'wp_rest' ),
			'postId'          => $this->get_current_post_id(),
			'defaultPrompt'   => '' !== $awfah_exp['prompt'] ? $awfah_exp['prompt'] : $default_prompts['generate-excerpt'],
			'enabled'         => $awfah_exp['enabled'],
			'defaultProvider' => $awfah_exp['provider'],
			'tones'           => [
				[
					'value' => '',
					'label' => __( 'Default', 'ai-workflow-automation-ai-agent-hub' ),
				],
				[
					'value' => 'professional',
					'label' => __( 'Professional', 'ai-workflow-automation-ai-agent-hub' ),
				],
				[
					'value' => 'casual',
					'label' => __( 'Casual', 'ai-workflow-automation-ai-agent-hub' ),
				],
				[
					'value' => 'friendly',
					'label' => __( 'Friendly', 'ai-workflow-automation-ai-agent-hub' ),
				],
				[
					'value' => 'academic',
					'label' => __( 'Academic', 'ai-workflow-automation-ai-agent-hub' ),
				],
			],
		];
	}

	/**
	 * Localized config for the image generation experiment.
	 *
	 * Shared by the block editor and Classic Editor enqueue paths.
	 *
	 * @return array<string, mixed>
	 */
	protected function get_image_config(): array {
		$default_prompts = $this->get_default_prompts();
		$awfah_exp       = \AtlasAiDev\Awfah\REST\Experiments_Controller::get_experiment_settings( 'image-generation' );

		return [
			'isPro'           => awfah_is_pro_active(),
			'abilitySlug'     => 'awfah-content/generate-feature-image',
			'abilityPath'     => rest_url( 'wp-abilities/v1/abilities/awfah-content/generate-feature-image/run' ),
			'promptsUrl'      => rest_url( 'awfah/v1/prompts/image-generation' ),
			'templatesUrl'    => rest_url( 'awfah/v1/prompts/image-generation/templates' ),
			'explainUrl'      => rest_url( 'awfah/v1/prompts/image-generation/explain' ),
			'providersUrl'    => rest_url( 'awfah/v1/providers' ),
			'modelsUrlBase'   => rest_url( 'awfah/v1/providers' ),
			'wpNonce'         => wp_create_nonce( 'wp_rest' ),
			'postId'          => $this->get_current_post_id(),
			'defaultPrompt'   => '' !== $awfah_exp['prompt'] ? $awfah_exp['prompt'] : $default_prompts['image-generation'],
			'enabled'         => $awfah_exp['enabled'],
			'defaultProvider' => $awfah_exp['provider'],
			'styles'          => [
				[
					'value' => '',
					'label' => __( 'Default', 'ai-workflow-automation-ai-agent-hub' ),
				],
				[
					'value' => 'photo-realistic',
					'label' => __( 'Photo-realistic', 'ai-workflow-automation-ai-agent-hub' ),
				],
				[
					'value' => 'illustration',
					'label' => __( 'Illustration', 'ai-workflow-automation-ai-agent-hub' ),
				],
				[
					'value' => 'abstract',
					'label' => __( 'Abstract', 'ai-workflow-automation-ai-agent-hub' ),
				],
				[
					'value' => 'minimalist',
					'label' => __( 'Minimalist', 'ai-workflow-automation-ai-agent-hub' ),
				],
				[
					'value' => 'watercolor',
					'label' => __( 'Watercolor', 'ai-workflow-automation-ai-agent-hub' ),
				],
			],
		];
	}

	/**
	 * Localized config for the summarization experiment.
	 *
	 * Shared by the block editor and Classic Editor enqueue paths.
	 *
	 * @return array<string, mixed>
	 */
	protected function get_summarization_config(): array {
		$default_prompts = $this->get_default_prompts();
		$awfah_exp       = \AtlasAiDev\Awfah\REST\Experiments_Controller::get_experiment_settings( 'summarization' );

		return [
			'isPro'           => awfah_is_pro_active(),
			'abilitySlug'     => 'awfah-content/summarize',
			'abilityPath'     => rest_url( 'wp-abilities/v1/abilities/awfah-content/summarize/run' ),
			'promptsUrl'      => rest_url( 'awfah/v1/prompts/summarization' ),
			'templatesUrl'    => rest_url( 'awfah/v1/prompts/summarization/templates' ),
			'explainUrl'      => rest_url( 'awfah/v1/prompts/summarization/explain' ),
			'providersUrl'    => rest_url( 'awfah/v1/providers' ),
			'modelsUrlBase'   => rest_url( 'awfah/v1/providers' ),
			'wpNonce'         => wp_create_nonce( 'wp_rest' ),
			'postId'          => $this->get_current_post_id(),
			'defaultPrompt'   => '' !== $awfah_exp['prompt'] ? $awfah_exp['prompt'] : $default_prompts['summarization'],
			'enabled'         => $awfah_exp['enabled'],
			'defaultProvider' => $awfah_exp['provider'],
			'lengths'         => [
				[
					'value' => 'short',
					'label' => __( 'Short', 'ai-workflow-automation-ai-agent-hub' ),
				],
				[
					'value' => 'medium',
					'label' => __( 'Medium', 'ai-workflow-automation-ai-agent-hub' ),
				],
				[
					'value' => 'long',
					'label' => __( 'Long', 'ai-workflow-automation-ai-agent-hub' ),
				],
			],
		];
	}

	/**
	 * Localized config for the title generation experiment.
	 *
	 * Shared by the block editor and Classic Editor enqueue paths.
	 *
	 * @return array<string, mixed>
	 */
	protected function get_title_config(): array {
		$default_prompts = $this->get_default_prompts();
		$awfah_exp       = \AtlasAiDev\Awfah\REST\Experiments_Controller::get_experiment_settings( 'suggest-titles' );

		return [
			'isPro'           => awfah_is_pro_active(),
			'abilitySlug'     => 'awfah-content/suggest-titles',
			'abilityPath'     => rest_url( 'wp-abilities/v1/abilities/awfah-content/suggest-titles/run' ),
			'promptsUrl'      => rest_url( 'awfah/v1/prompts/suggest-titles' ),
			'templatesUrl'    => rest_url( 'awfah/v1/prompts/suggest-titles/templates' ),
			'explainUrl'      => rest_url( 'awfah/v1/prompts/suggest-titles/explain' ),
			'providersUrl'    => rest_url( 'awfah/v1/providers' ),
			'modelsUrlBase'   => rest_url( 'awfah/v1/providers' ),
			'wpNonce'         => wp_create_nonce( 'wp_rest' ),
			'postId'          => $this->get_current_post_id(),
			'defaultPrompt'   => '' !== $awfah_exp['prompt'] ? $awfah_exp['prompt'] : $default_prompts['suggest-titles'],
			'enabled'         => $awfah_exp['enabled'],
			'defaultProvider' => $awfah_exp['provider'],
			'candidates'      => 5,
		];
	}

	/**
	 * Localized config for the alt-text generation experiment.
	 *
	 * Shared by the block editor and Classic Editor enqueue paths.
	 *
	 * @return array<string, mixed>
	 */
	protected function get_alt_text_config(): array {
		$default_prompts = $this->get_default_prompts();
		$awfah_exp       = \AtlasAiDev\Awfah\REST\Experiments_Controller::get_experiment_settings( 'alt-text-generation' );

		return [
			'isPro'           => awfah_is_pro_active(),
			'abilityPath'     => rest_url( 'wp-abilities/v1/abilities/awfah-content/generate-alt-text/run' ),
			'promptsUrl'      => rest_url( 'awfah/v1/prompts/alt-text-generation' ),
			'explainUrl'      => rest_url( 'awfah/v1/prompts/alt-text-generation/explain' ),
			'providersUrl'    => rest_url( 'awfah/v1/providers' ),
			'modelsUrlBase'   => rest_url( 'awfah/v1/providers' ),
			'wpNonce'         => wp_create_nonce( 'wp_rest' ),
			'defaultPrompt'   => '' !== $awfah_exp['prompt'] ? $awfah_exp['prompt'] : $default_prompts['alt-text-generation'],
			'enabled'         => $awfah_exp['enabled'],
			'defaultProvider' => $awfah_exp['provider'],
		];
	}
}
