<?php

namespace AtlasAiDev\Awfah\Abilities;

use WP_Error;
use WP_REST_Request;

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

class Custom_Post_Types_Abilities {

	public static function get_abilities(): array {
		return [
			[
				'id'           => 'awfah-cpt/wp-list-post-types',
				'module'       => 'cpt_manager',
				'label'        => __( 'List Post Types', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'List all available WordPress custom post types.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-cpt',
				'input_schema' => [ 'type' => 'object', 'properties' => (object) [] ],
				'meta'         => [
					'show_in_rest' => true,
					'mcp'          => [ 'public' => true ],
					'uri'          => 'wordpress://ai-agent-hub/post-types',
					'mimeType'     => 'application/json',
				],
			],
			[
				'id'           => 'awfah-cpt/wp-cpt-search',
				'module'       => 'cpt_manager',
				'label'        => __( 'Search Custom Post Types', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Search and filter WordPress custom post types with pagination.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-cpt',
				'input_schema' => [
					'type'       => 'object',
					'required'   => [ 'post_type' ],
					'properties' => [
						'post_type' => [ 'type' => 'string', 'description' => __( 'The custom post type to search.', 'ai-workflow-automation-ai-agent-hub' ) ],
						'search'    => [ 'type' => 'string' ],
						'author'    => [ 'type' => 'integer' ],
						'status'    => [ 'type' => 'string', 'default' => 'publish' ],
						'page'      => [ 'type' => 'integer', 'default' => 1 ],
						'per_page'  => [ 'type' => 'integer', 'default' => 10 ],
					],
				],
				'meta'         => [
					'show_in_rest' => true,
					'mcp'          => [ 'public' => true ],
					'uri'          => 'wordpress://ai-agent-hub/post-types/{post_type}',
					'mimeType'     => 'application/json',
				],
			],
			[
				'id'           => 'awfah-cpt/wp-get-cpt',
				'module'       => 'cpt_manager',
				'label'        => __( 'Get Custom Post Type', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Get a WordPress custom post type by ID.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-cpt',
				'input_schema' => [
					'type'       => 'object',
					'required'   => [ 'post_type', 'id' ],
					'properties' => [
						'post_type' => [ 'type' => 'string' ],
						'id'        => [ 'type' => 'integer' ],
					],
				],
				'meta'         => [
					'show_in_rest' => true,
					'mcp'          => [ 'public' => true ],
					'uri'          => 'wordpress://ai-agent-hub/post-types/{post_type}/{id}',
					'mimeType'     => 'application/json',
				],
			],
			[
				'id'           => 'awfah-cpt/wp-add-cpt',
				'module'       => 'cpt_manager',
				'label'        => __( 'Add Custom Post Type', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Add a new WordPress custom post type.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-cpt',
				'input_schema' => [
					'type'       => 'object',
					'required'   => [ 'post_type', 'title', 'content' ],
					'properties' => [
						'post_type' => [ 'type' => 'string' ],
						'title'     => [ 'type' => 'string' ],
						'content'   => [ 'type' => 'string', 'description' => __( 'The content in valid Gutenberg block format.', 'ai-workflow-automation-ai-agent-hub' ) ],
						'excerpt'   => [ 'type' => 'string' ],
						'status'    => [ 'type' => 'string', 'default' => 'draft' ],
					],
				],
				'meta'         => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ] ],
			],
			[
				'id'           => 'awfah-cpt/wp-update-cpt',
				'module'       => 'cpt_manager',
				'label'        => __( 'Update Custom Post Type', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Update a WordPress custom post type by ID.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-cpt',
				'input_schema' => [
					'type'       => 'object',
					'required'   => [ 'post_type', 'id' ],
					'properties' => [
						'post_type' => [ 'type' => 'string' ],
						'id'        => [ 'type' => 'integer' ],
						'title'     => [ 'type' => 'string' ],
						'content'   => [ 'type' => 'string' ],
						'excerpt'   => [ 'type' => 'string' ],
						'status'    => [ 'type' => 'string' ],
					],
				],
				'meta'         => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ] ],
			],
			[
				'id'           => 'awfah-cpt/wp-delete-cpt',
				'module'       => 'cpt_manager',
				'label'        => __( 'Delete Custom Post Type', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Delete a WordPress custom post type by ID.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-cpt',
				'input_schema' => [
					'type'       => 'object',
					'required'   => [ 'post_type', 'id' ],
					'properties' => [
						'post_type' => [ 'type' => 'string' ],
						'id'        => [ 'type' => 'integer' ],
					],
				],
				'meta'         => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ] ],
			],
		];
	}

	public static function register(): void {
		if ( ! function_exists( 'wp_register_ability' ) ) {
			return;
		}
		$callbacks = [
			'awfah-cpt/wp-list-post-types' => [ __CLASS__, 'execute_list_post_types' ],
			'awfah-cpt/wp-cpt-search'      => [ __CLASS__, 'execute_cpt_search' ],
			'awfah-cpt/wp-get-cpt'         => [ __CLASS__, 'execute_get_cpt' ],
			'awfah-cpt/wp-add-cpt'         => [ __CLASS__, 'execute_add_cpt' ],
			'awfah-cpt/wp-update-cpt'      => [ __CLASS__, 'execute_update_cpt' ],
			'awfah-cpt/wp-delete-cpt'      => [ __CLASS__, 'execute_delete_cpt' ],
		];
		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_posts' );
				},
			] ) );
		}
	}

	public static function execute_list_post_types( $input = null ) {
		$request  = new WP_REST_Request( 'GET', '/wp/v2/types' );
		$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() );
		}
		$data = $response->get_data();
		if ( is_array( $data ) && array_is_list( $data ) ) {
			return [ 'results' => $data ];
		}
		return $data;
	}

	public static function execute_cpt_search( $input = null ) {
		$input     = (array) $input;
		$post_type = sanitize_text_field( $input['post_type'] ?? '' );
		$page      = max( 1, (int) ( $input['page'] ?? 1 ) );
		$per_page  = max( 1, (int) ( $input['per_page'] ?? 10 ) );
		$args      = [
			'post_type'      => $post_type,
			'posts_per_page' => $per_page,
			'paged'          => $page,
			'post_status'    => sanitize_text_field( $input['status'] ?? 'publish' ),
		];
		if ( ! empty( $input['search'] ) ) {
			$args['s'] = sanitize_text_field( $input['search'] );
		}
		if ( ! empty( $input['author'] ) ) {
			$args['author'] = (int) $input['author'];
		}
		$query = new \WP_Query( $args );
		return [
			'results'  => $query->posts,
			'total'    => $query->found_posts,
			'pages'    => $query->max_num_pages,
			'page'     => $page,
			'per_page' => $per_page,
		];
	}

	public static function execute_get_cpt( $input = null ) {
		$input = (array) $input;
		$post  = get_post( (int) ( $input['id'] ?? 0 ) );
		if ( ! $post || $post->post_type !== ( $input['post_type'] ?? '' ) ) {
			return new WP_Error( 'not_found', __( 'Post not found.', 'ai-workflow-automation-ai-agent-hub' ) );
		}
		return (array) $post;
	}

	public static function execute_add_cpt( $input = null ) {
		$input     = (array) $input;
		$post_data = [
			'post_type'    => sanitize_text_field( $input['post_type'] ?? '' ),
			'post_title'   => sanitize_text_field( $input['title'] ?? '' ),
			'post_content' => wp_kses_post( $input['content'] ?? '' ),
			'post_status'  => sanitize_text_field( $input['status'] ?? 'draft' ),
		];
		if ( ! empty( $input['excerpt'] ) ) {
			$post_data['post_excerpt'] = sanitize_text_field( $input['excerpt'] );
		}
		$post_id = wp_insert_post( $post_data, true );
		if ( is_wp_error( $post_id ) ) {
			return $post_id;
		}
		return (array) get_post( $post_id );
	}

	public static function execute_update_cpt( $input = null ) {
		$input = (array) $input;
		$post  = get_post( (int) ( $input['id'] ?? 0 ) );
		if ( ! $post || $post->post_type !== ( $input['post_type'] ?? '' ) ) {
			return new WP_Error( 'not_found', __( 'Post not found.', 'ai-workflow-automation-ai-agent-hub' ) );
		}
		$post_data = [ 'ID' => $post->ID ];
		if ( ! empty( $input['title'] ) ) {
			$post_data['post_title'] = sanitize_text_field( $input['title'] );
		}
		if ( ! empty( $input['content'] ) ) {
			$post_data['post_content'] = wp_kses_post( $input['content'] );
		}
		if ( ! empty( $input['excerpt'] ) ) {
			$post_data['post_excerpt'] = sanitize_text_field( $input['excerpt'] );
		}
		if ( ! empty( $input['status'] ) ) {
			$post_data['post_status'] = sanitize_text_field( $input['status'] );
		}
		$post_id = wp_update_post( $post_data, true );
		if ( is_wp_error( $post_id ) ) {
			return $post_id;
		}
		return (array) get_post( $post_id );
	}

	public static function execute_delete_cpt( $input = null ) {
		$input = (array) $input;
		$post  = get_post( (int) ( $input['id'] ?? 0 ) );
		if ( ! $post || $post->post_type !== ( $input['post_type'] ?? '' ) ) {
			return new WP_Error( 'not_found', __( 'Post not found.', 'ai-workflow-automation-ai-agent-hub' ) );
		}
		$result = wp_delete_post( $post->ID, true );
		if ( ! $result ) {
			return new WP_Error( 'delete_failed', __( 'Failed to delete post.', 'ai-workflow-automation-ai-agent-hub' ) );
		}
		return [ 'deleted' => true, 'id' => $post->ID ];
	}
}
