<?php

namespace AtlasAiDev\Awfah\Admin;

use AtlasAiDev\Awfah\Integrations\Wpai_Bridge;
use AtlasAiDev\Awfah\Plugin;

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

/**
 * Classic Editor support for the AI editor experiments.
 *
 * Extends Editor_Experiments to inherit the shared per-experiment
 * localization config builders (single source of truth for both the block
 * editor and classic paths) while registering only classic-screen hooks —
 * the parent constructor (block editor hooks + meta registration) is
 * intentionally not called.
 */
class Classic_Experiments extends Editor_Experiments {

	/**
	 * Experiment slugs allowed on the current classic screen (cached per request).
	 *
	 * @var string[]|null
	 */
	private ?array $allowed_experiments = null;

	public function __construct() {
		// Intentionally NOT calling parent::__construct() — the parent wires
		// enqueue_block_editor_assets + meta registration, which the block
		// editor instance already handles.
		add_action( 'add_meta_boxes', [ $this, 'register_summary_meta_box' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_classic_experiments' ] );
	}

	/**
	 * Whether the current screen is a classic (non-block) post edit screen.
	 *
	 * @return bool
	 */
	private function is_classic_post_screen(): bool {
		if ( ! function_exists( 'get_current_screen' ) ) {
			return false;
		}

		$screen = get_current_screen();

		if ( ! $screen || 'post' !== $screen->base ) {
			return false;
		}

		return ! $screen->is_block_editor();
	}

	/**
	 * Experiments allowed on the current classic screen, honoring the same
	 * gating as the block editor path: content_steward module, per-experiment
	 * Wpai_Bridge toggles, and post-type support checks.
	 *
	 * @return string[] Experiment slugs.
	 */
	private function get_allowed_experiments(): array {
		if ( null !== $this->allowed_experiments ) {
			return $this->allowed_experiments;
		}

		$this->allowed_experiments = [];

		$settings = Plugin::get_settings();
		if ( empty( $settings['modules']['content_steward'] ) ) {
			return $this->allowed_experiments;
		}

		$screen    = get_current_screen();
		$post_type = $screen ? $screen->post_type : '';

		if ( 'attachment' !== $post_type ) {
			if ( post_type_supports( $post_type, 'excerpt' ) && Wpai_Bridge::is_experiment_allowed( 'generate-excerpt' ) ) {
				$this->allowed_experiments[] = 'generate-excerpt';
			}

			if ( post_type_supports( $post_type, 'thumbnail' ) && Wpai_Bridge::is_experiment_allowed( 'image-generation' ) ) {
				$this->allowed_experiments[] = 'image-generation';
			}

			if ( post_type_supports( $post_type, 'editor' ) && Wpai_Bridge::is_experiment_allowed( 'summarization' ) ) {
				$this->allowed_experiments[] = 'summarization';
			}

			if ( post_type_supports( $post_type, 'title' ) && Wpai_Bridge::is_experiment_allowed( 'suggest-titles' ) ) {
				$this->allowed_experiments[] = 'suggest-titles';
			}
		}

		// Alt-text runs in the media modal, available on any post screen.
		if ( Wpai_Bridge::is_experiment_allowed( 'alt-text-generation' ) ) {
			$this->allowed_experiments[] = 'alt-text-generation';
		}

		return $this->allowed_experiments;
	}

	/**
	 * Register the "AtlasAI Summary" meta box (classic screens only).
	 * The box renders an empty container; the classic bundle mounts the
	 * summarization UI into it.
	 */
	public function register_summary_meta_box(): void {
		if ( ! $this->is_classic_post_screen() ) {
			return;
		}

		if ( ! in_array( 'summarization', $this->get_allowed_experiments(), true ) ) {
			return;
		}

		add_meta_box(
			'aah-classic-summary',
			'AtlasAI ' . __( 'Summary', 'ai-workflow-automation-ai-agent-hub' ),
			[ $this, 'render_summary_meta_box' ],
			null,
			'side',
			'default'
		);
	}

	/**
	 * Render the summary meta box container.
	 */
	public function render_summary_meta_box(): void {
		echo '<div id="aah-classic-summarization-root"></div>';
	}

	/**
	 * Enqueue the classic experiments bundle on classic post edit screens,
	 * localizing the same config objects the block editor bundles receive.
	 *
	 * @param string $hook_suffix Current admin page hook suffix.
	 */
	public function enqueue_classic_experiments( string $hook_suffix ): void {
		if ( ! in_array( $hook_suffix, [ 'post.php', 'post-new.php' ], true ) ) {
			return;
		}

		if ( ! $this->is_classic_post_screen() ) {
			return;
		}

		$allowed = $this->get_allowed_experiments();
		if ( empty( $allowed ) ) {
			return;
		}

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

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

		$asset = require $asset_file;

		wp_enqueue_script(
			'aah-classic-experiments',
			$build_url . 'index.js',
			array_merge( $asset['dependencies'] ?? [], [ 'jquery', 'media-editor' ] ),
			$asset['version'] ?? AWFAH_VERSION,
			true
		);

		// Classic screens do not load the wp-components stylesheet — the
		// experiment UIs are built entirely on @wordpress/components.
		wp_enqueue_style( 'wp-components' );

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

		// Localize only the allowed experiments; a missing config object makes
		// the corresponding UI a graceful no-op in the bundle.
		if ( in_array( 'generate-excerpt', $allowed, true ) ) {
			wp_localize_script( 'aah-classic-experiments', 'aahExcerptGeneration', $this->get_excerpt_config() );
		}

		if ( in_array( 'image-generation', $allowed, true ) ) {
			wp_localize_script( 'aah-classic-experiments', 'aahImageGeneration', $this->get_image_config() );
		}

		if ( in_array( 'summarization', $allowed, true ) ) {
			wp_localize_script( 'aah-classic-experiments', 'aahSummarization', $this->get_summarization_config() );
		}

		if ( in_array( 'suggest-titles', $allowed, true ) ) {
			wp_localize_script( 'aah-classic-experiments', 'aahTitleGeneration', $this->get_title_config() );
		}

		if ( in_array( 'alt-text-generation', $allowed, true ) ) {
			wp_localize_script( 'aah-classic-experiments', 'aahAltTextGeneration', $this->get_alt_text_config() );
		}
	}
}
