<?php

namespace AtlasAiDev\Awfah\Abilities;

use WP_Error;
use WP_REST_Request;

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

/**
 * Registers WordPress page CRUD abilities using the Abilities API.
 *
 * @package AtlasAiDev\Awfah\Abilities
 */
class Pages_Abilities {

	/**
	 * Return the full list of ability definitions.
	 *
	 * @return array[]
	 */
	public static function get_abilities(): array {
		return [
			[
				'id'           => 'awfah-pages/wp-pages-search',
				'module'       => 'pages_manager',
				'label'        => __( 'Search Pages', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Search and filter WordPress pages with pagination.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-pages',
				'input_schema' => [
					'type'       => 'object',
					'properties' => [
						'search'   => [
							'type'        => 'string',
							'description' => __( 'Limit results to those matching a string.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'page'     => [
							'type'        => 'integer',
							'description' => __( 'Current page of the collection.', 'ai-workflow-automation-ai-agent-hub' ),
							'default'     => 1,
							'minimum'     => 1,
						],
						'per_page' => [
							'type'        => 'integer',
							'description' => __( 'Maximum number of items to be returned in result set.', 'ai-workflow-automation-ai-agent-hub' ),
							'default'     => 10,
							'minimum'     => 1,
							'maximum'     => 100,
						],
						'status'   => [
							'type'        => 'string',
							'description' => __( 'Limit result set to pages assigned one or more statuses.', 'ai-workflow-automation-ai-agent-hub' ),
							'default'     => 'publish',
						],
						'orderby'  => [
							'type'        => 'string',
							'description' => __( 'Sort collection by page attribute.', 'ai-workflow-automation-ai-agent-hub' ),
							'enum'        => [ 'date', 'relevance', 'id', 'include', 'title', 'slug', 'modified', 'menu_order' ],
							'default'     => 'date',
						],
						'order'    => [
							'type'        => 'string',
							'description' => __( 'Order sort attribute ascending or descending.', 'ai-workflow-automation-ai-agent-hub' ),
							'enum'        => [ 'asc', 'desc' ],
							'default'     => 'desc',
						],
					],
				],
				'meta'         => [
					'show_in_rest' => true,
					'mcp'          => [ 'public' => true ],
					'uri'          => 'wordpress://ai-agent-hub/pages',
					'mimeType'     => 'application/json',
				],
			],
			[
				'id'           => 'awfah-pages/wp-get-page',
				'module'       => 'pages_manager',
				'label'        => __( 'Get Page', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Get a WordPress page by ID.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-pages',
				'input_schema' => [
					'type'       => 'object',
					'required'   => [ 'id' ],
					'properties' => [
						'id'      => [
							'type'        => 'integer',
							'description' => __( 'The ID of the page.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'context' => [
							'type'        => 'string',
							'description' => __( 'Scope under which the request is made.', 'ai-workflow-automation-ai-agent-hub' ),
							'enum'        => [ 'view', 'embed', 'edit' ],
							'default'     => 'view',
						],
					],
				],
				'meta'         => [
					'show_in_rest' => true,
					'mcp'          => [ 'public' => true ],
					'uri'          => 'wordpress://ai-agent-hub/pages/{id}',
					'mimeType'     => 'application/json',
				],
			],
			[
				'id'           => 'awfah-pages/wp-add-page',
				'module'       => 'pages_manager',
				'label'        => __( 'Add Page', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Add a new WordPress page.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-pages',
				'input_schema' => [
					'type'       => 'object',
					'required'   => [ 'title', 'content' ],
					'properties' => [
						'title'   => [
							'type'        => 'string',
							'description' => __( 'The title for the page.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'content' => [
							'type'        => 'string',
							'description' => __( 'The content of the page in a valid Gutenberg block format.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'status'  => [
							'type'        => 'string',
							'description' => __( 'A named status for the page.', 'ai-workflow-automation-ai-agent-hub' ),
							'enum'        => [ 'publish', 'future', 'draft', 'pending', 'private' ],
							'default'     => 'draft',
						],
						'excerpt' => [
							'type'        => 'string',
							'description' => __( 'The excerpt for the page.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'parent'  => [
							'type'        => 'integer',
							'description' => __( 'The ID of the parent page.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'menu_order' => [
							'type'        => 'integer',
							'description' => __( 'The order of the page in the menu.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'author'  => [
							'type'        => 'integer',
							'description' => __( 'The ID for the author of the page.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'slug'    => [
							'type'        => 'string',
							'description' => __( 'An alphanumeric identifier for the page unique to its type.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'featured_media' => [
							'type'        => 'integer',
							'description' => __( 'The ID of the featured media for the page.', 'ai-workflow-automation-ai-agent-hub' ),
						],
					],
				],
				'meta'         => [
					'show_in_rest' => true,
					'mcp'          => [ 'public' => true ],
				],
			],
			[
				'id'           => 'awfah-pages/wp-update-page',
				'module'       => 'pages_manager',
				'label'        => __( 'Update Page', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Update a WordPress page by ID.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-pages',
				'input_schema' => [
					'type'       => 'object',
					'required'   => [ 'id' ],
					'properties' => [
						'id'      => [
							'type'        => 'integer',
							'description' => __( 'The ID of the page to update.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'title'   => [
							'type'        => 'string',
							'description' => __( 'The title for the page.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'content' => [
							'type'        => 'string',
							'description' => __( 'The content of the page in a valid Gutenberg block format.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'status'  => [
							'type'        => 'string',
							'description' => __( 'A named status for the page.', 'ai-workflow-automation-ai-agent-hub' ),
							'enum'        => [ 'publish', 'future', 'draft', 'pending', 'private' ],
						],
						'excerpt' => [
							'type'        => 'string',
							'description' => __( 'The excerpt for the page.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'parent'  => [
							'type'        => 'integer',
							'description' => __( 'The ID of the parent page.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'menu_order' => [
							'type'        => 'integer',
							'description' => __( 'The order of the page in the menu.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'author'  => [
							'type'        => 'integer',
							'description' => __( 'The ID for the author of the page.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'slug'    => [
							'type'        => 'string',
							'description' => __( 'An alphanumeric identifier for the page unique to its type.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'featured_media' => [
							'type'        => 'integer',
							'description' => __( 'The ID of the featured media for the page.', 'ai-workflow-automation-ai-agent-hub' ),
						],
					],
				],
				'meta'         => [
					'show_in_rest' => true,
					'mcp'          => [ 'public' => true ],
				],
			],
			[
				'id'           => 'awfah-pages/wp-delete-page',
				'module'       => 'pages_manager',
				'label'        => __( 'Delete Page', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Delete a WordPress page by ID.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-pages',
				'input_schema' => [
					'type'       => 'object',
					'required'   => [ 'id' ],
					'properties' => [
						'id'    => [
							'type'        => 'integer',
							'description' => __( 'The ID of the page to delete.', 'ai-workflow-automation-ai-agent-hub' ),
						],
						'force' => [
							'type'        => 'boolean',
							'description' => __( 'Whether to bypass Trash and force deletion.', 'ai-workflow-automation-ai-agent-hub' ),
							'default'     => false,
						],
					],
				],
				'meta'         => [
					'show_in_rest' => true,
					'mcp'          => [ 'public' => true ],
				],
			],
		];
	}

	/**
	 * Register all page-related abilities with the Abilities API.
	 */
	public static function register(): void {
		if ( ! function_exists( 'wp_register_ability' ) ) {
			return;
		}

		$callbacks = [
			'awfah-pages/wp-pages-search' => [ __CLASS__, 'execute_search_pages' ],
			'awfah-pages/wp-get-page'     => [ __CLASS__, 'execute_get_page' ],
			'awfah-pages/wp-add-page'     => [ __CLASS__, 'execute_add_page' ],
			'awfah-pages/wp-update-page'  => [ __CLASS__, 'execute_update_page' ],
			'awfah-pages/wp-delete-page'  => [ __CLASS__, 'execute_delete_page' ],
		];

		foreach ( self::get_abilities() as $ability ) {
			$config = $ability;
			$id     = $ability['id'];
			unset( $config['id'], $config['module'] );

			// Workaround: MCP ResourcesHandler calls execute() with no input.
			// Adding default empty object prevents "input is not of type object" validation error.
			if ( isset( $config['meta']['uri'], $config['input_schema']['type'] ) && 'object' === $config['input_schema']['type'] ) {
				$config['input_schema']['default'] = (object) [];
			}

			wp_register_ability(
				$id,
				array_merge(
					$config,
					[
						'execute_callback'    => $callbacks[ $id ],
						'permission_callback' => static function () use ( $id ) {
							return \AtlasAiDev\Awfah\Plugin::check_ability_access( $id, 'edit_pages' );
						},
					]
				)
			);
		}
	}

	public static function execute_search_pages( $input = null ) {
		return self::dispatch_rest( 'GET', '/wp/v2/pages', (array) $input );
	}

	public static function execute_get_page( $input = null ) {
		$input = (array) $input;
		$id    = isset( $input['id'] ) ? (int) $input['id'] : 0;
		unset( $input['id'] );
		return self::dispatch_rest( 'GET', '/wp/v2/pages/' . $id, $input );
	}

	public static function execute_add_page( $input = null ) {
		return self::dispatch_rest( 'POST', '/wp/v2/pages', (array) $input );
	}

	public static function execute_update_page( $input = null ) {
		$input = (array) $input;
		$id    = isset( $input['id'] ) ? (int) $input['id'] : 0;
		unset( $input['id'] );
		return self::dispatch_rest( 'POST', '/wp/v2/pages/' . $id, $input );
	}

	public static function execute_delete_page( $input = null ) {
		$input = (array) $input;
		$id    = isset( $input['id'] ) ? (int) $input['id'] : 0;
		unset( $input['id'] );
		return self::dispatch_rest( 'DELETE', '/wp/v2/pages/' . $id, $input );
	}

	private static function dispatch_rest( string $method, string $route, array $params = [] ) {
		$request = new WP_REST_Request( $method, $route );
		foreach ( $params as $key => $value ) {
			$request->set_param( $key, $value );
		}
		$response = rest_do_request( $request );
		if ( $response->is_error() ) {
			$error = $response->as_error();
			return new WP_Error( $error->get_error_code(), $error->get_error_message(), [ 'status' => $response->get_status() ] );
		}
		$data = $response->get_data();
		if ( is_array( $data ) && array_is_list( $data ) ) {
			return [ 'results' => $data ];
		}
		return $data;
	}
}
