<?php
/**
 * PufferGo Tool - Loader
 *
 * Enqueues the PufferGo Tool sidebar on post/page edit screens.
 *
 * @package PufferGo_Core
 */

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

/**
 * Class PufferGo_Tool
 */
class PufferGo_Tool {

	const VERSION = '1.0.0';

	/**
	 * Constructor.
	 */
	public function __construct() {
		if ( is_admin() ) {
			add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_editor_assets' ) );
		}
		add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) );
	}

	/**
	 * Register REST route for HTML import proxy (forwards to external process-html API).
	 */
	public function register_rest_routes() {
		register_rest_route(
			'puffergo/v1',
			'/ai/process-html',
			array(
				'methods'             => 'POST',
				'permission_callback' => function () {
					return current_user_can( 'edit_posts' );
				},
				'callback'            => array( $this, 'rest_import_process_html' ),
				'args'                => array(
					'html'            => array(
						'required'          => true,
						'type'              => 'string',
						'sanitize_callback' => null,
					),
					'compilerConfig'  => array(
						'required' => false,
						'type'     => 'object',
						'default'  => array(),
					),
				),
			)
		);

		register_rest_route(
			'puffergo/v1',
			'/unit-config',
			array(
				'methods'             => 'GET',
				'permission_callback' => function () {
					return current_user_can( 'edit_posts' );
				},
				'callback'            => array( $this, 'rest_get_unit_config' ),
			)
		);
	}

	/**
	 * Get unit configuration.
	 *
	 * @return WP_REST_Response
	 */
	public function rest_get_unit_config() {
		if ( ! class_exists( 'PufferGo_Unit_Config' ) ) {
			require_once PUFFERGO_PLUGIN_DIR . 'php/config/class-puffergo-unit-config.php';
		}
		$config = PufferGo_Unit_Config::format_for_js();
		return new WP_REST_Response( $config, 200 );
	}

	/**
	 * Proxy request to external process-html API.
	 * Uses the same base URL as generate (PufferGo_API_Client).
	 * External URL: {{baseUrl}}/api/ai/process-html (e.g. https://api.puffergo.com/api/ai/process-html).
	 *
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response
	 */
	public function rest_import_process_html( $request ) {
		$params = $request->get_json_params();
		if ( ! is_array( $params ) ) {
			$params = array();
		}
		$html = isset( $params['html'] ) ? $params['html'] : '';
		$compiler_config = isset( $params['compilerConfig'] ) && is_array( $params['compilerConfig'] ) ? $params['compilerConfig'] : array();

		if ( ! is_string( $html ) || trim( $html ) === '' ) {
			return new WP_REST_Response(
				array(
					'success' => false,
					'message' => __( 'HTML content is required.', 'puffergo' ),
				),
				400
			);
		}

		if ( ! class_exists( 'PufferGo_API_Client' ) ) {
			return new WP_REST_Response(
				array(
					'success' => false,
					'message' => __( 'API client is not available.', 'puffergo' ),
				),
				503
			);
		}

		try {
			$api_client = PufferGo_API_Client::get_instance();
			$data      = $api_client->post(
				'/api/ai/process-html',
				array(
					'html'           => $html,
					'compilerConfig' => $compiler_config,
				),
				array(
					'timeout'    => 60,
					'log_prefix' => 'PufferGo Import',
				)
			);
			return new WP_REST_Response(
				array(
					'success' => true,
					'data'    => is_array( $data ) ? $data : array( 'processedHtml' => '', 'tailwindCss' => '', 'dependencies' => array() ),
				),
				200
			);
		} catch ( PufferGo_API_Exception $e ) {
			return new WP_REST_Response( $e->toArray(), $e->getCode() );
		} catch ( Exception $e ) {
			return new WP_REST_Response(
				array(
					'success' => false,
					'message' => $e->getMessage(),
				),
				500
			);
		}
	}

	/**
	 * Enqueue assets for the block editor (post/post-new only).
	 */
	public function enqueue_editor_assets() {
		$screen = get_current_screen();
		if ( ! $screen || ! in_array( $screen->base, array( 'post', 'post-new' ), true ) ) {
			return;
		}

		$plugin_url = plugin_dir_url( dirname( __FILE__ ) );
		$plugin_dir = plugin_dir_path( dirname( __FILE__ ) );
		$asset_file = $plugin_dir . 'build/admin/puffergo-tool/index.asset.php';

		if ( file_exists( $asset_file ) ) {
			$asset   = include $asset_file;
			$deps    = $asset['dependencies'];
			$version = $asset['version'];
		} else {
			$deps    = array(
				'wp-plugins',
				'wp-edit-post',
				'wp-editor',
				'wp-element',
				'wp-components',
				'wp-data',
				'wp-api-fetch',
				'wp-blocks',
				'wp-i18n',
				'wp-notices',
			);
			$version = self::VERSION;
		}

		$js_file = $plugin_dir . 'build/admin/puffergo-tool/index.js';
		if ( file_exists( $js_file ) ) {
			wp_enqueue_script(
				'puffergo-tool',
				$plugin_url . 'build/admin/puffergo-tool/index.js',
				$deps,
				$version,
				true
			);
			$feedback_url = class_exists( 'PufferGo_Telemetry' ) ? PufferGo_Telemetry::get_feedback_url() : '';
			$post_id = get_the_ID();
			$post_type = $post_id ? get_post_type( $post_id ) : '';
			$preview_url = '';
			if ( $post_id && $post_type === 'puffergo_product' ) {
				$preview_url = get_preview_post_link( $post_id );
			}
			wp_localize_script(
				'puffergo-tool',
				'puffergoTool',
				array(
					'restUrl'      => rest_url( 'puffergo/v1/' ),
					'nonce'        => wp_create_nonce( 'wp_rest' ),
					'feedbackUrl'  => $feedback_url,
					'hasApiKey'    => ! empty( get_option( 'puffergo_api_key', '' ) ),
					'connectUrl'   => PUFFERGO_BASE_URL . '/dashboard/connect',
					'siteName'     => get_bloginfo( 'name' ),
					'siteUrl'      => home_url( '/' ),
					'dashboardUrl' => admin_url( 'admin.php?page=puffergo' ),
					'postId'       => $post_id ? absint( $post_id ) : 0,
					'postType'     => $post_type ? sanitize_key( $post_type ) : '',
					'previewUrl'   => $preview_url,
				)
			);

			PufferGo_Workflow_Jobs_REST::add_poll_config_inline_script( 'puffergo-tool' );
		}

		$css_file = $plugin_dir . 'build/admin/puffergo-tool/style-index.css';
		if ( file_exists( $css_file ) ) {
			wp_enqueue_style(
				'puffergo-tool',
				$plugin_url . 'build/admin/puffergo-tool/style-index.css',
				array( 'wp-components' ),
				$version
			);
		}

		// SectionTree and other JS-imported CSS (from index.css chunk).
		$index_css = $plugin_dir . 'build/admin/puffergo-tool/index.css';
		if ( file_exists( $index_css ) ) {
			$index_deps = file_exists( $plugin_dir . 'build/admin/puffergo-tool/style-index.css' ) ? array( 'puffergo-tool' ) : array( 'wp-components' );
			wp_enqueue_style(
				'puffergo-tool-index',
				$plugin_url . 'build/admin/puffergo-tool/index.css',
				$index_deps,
				$version
			);
		}

		// Edit-tab styles (shared with Step4); ensures .puffergo-tool-edit-tab etc. load when not in admin index.css.
		$block_style_css = $plugin_dir . 'build/blocks/ai-site-builder-app/style-index.css';
		if ( file_exists( $block_style_css ) ) {
			wp_enqueue_style(
				'puffergo-tool-edit-tab-styles',
				$plugin_url . 'build/blocks/ai-site-builder-app/style-index.css',
				array( 'puffergo-tool-index' ),
				$version
			);
		}
	}
}

new PufferGo_Tool();
