<?php

namespace AtlasAiDev\Awfah\Abilities;

use WP_Error;
use WP_REST_Request;

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

class Settings_Abilities {

	public static function get_abilities(): array {
		return [
			[
				'id'           => 'awfah-settings/wp-get-settings',
				'module'       => 'settings_manager',
				'label'        => __( 'Get General Settings', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Get WordPress general site settings.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-settings',
				'input_schema' => [ 'type' => 'object', 'properties' => (object) [] ],
				'meta'         => [
					'show_in_rest' => true,
					'mcp'          => [ 'public' => true ],
					'uri'          => 'wordpress://ai-agent-hub/settings',
					'mimeType'     => 'application/json',
				],
			],
			[
				'id'           => 'awfah-settings/wp-update-settings',
				'module'       => 'settings_manager',
				'label'        => __( 'Update General Settings', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Update WordPress general site settings.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-settings',
				'input_schema' => [
					'type'       => 'object',
					'properties' => [
						'title'                  => [ 'type' => 'string', 'description' => 'Site title' ],
						'description'            => [ 'type' => 'string', 'description' => 'Site tagline/description' ],
						'timezone_string'        => [ 'type' => 'string', 'description' => 'Site timezone' ],
						'date_format'            => [ 'type' => 'string' ],
						'time_format'            => [ 'type' => 'string' ],
						'start_of_week'          => [ 'type' => 'integer', 'description' => '0 = Sunday, 1 = Monday, etc.' ],
						'language'               => [ 'type' => 'string' ],
						'posts_per_page'         => [ 'type' => 'integer' ],
						'default_category'       => [ 'type' => 'integer' ],
						'default_post_format'    => [ 'type' => 'string' ],
						'default_comment_status' => [ 'type' => 'string', 'enum' => [ 'open', 'closed' ] ],
						'default_ping_status'    => [ 'type' => 'string', 'enum' => [ 'open', 'closed' ] ],
					],
				],
				'meta'         => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true ] ],
			],
			[
				'id'           => 'awfah-settings/get-site-settings',
				'module'       => 'settings_manager',
				'label'        => __( 'Get Site Settings', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Provides detailed information about all WordPress site settings including general, reading, discussion, media, permalink, privacy, and writing.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-settings',
				'input_schema' => [ 'type' => 'object', 'properties' => (object) [] ],
				'meta'         => [
					'show_in_rest' => true,
					'mcp'          => [ 'public' => true ],
					'uri'          => 'wordpress://ai-agent-hub/settings/all',
					'mimeType'     => 'application/json',
				],
			],
		];
	}

	public static function register(): void {
		if ( ! function_exists( 'wp_register_ability' ) ) {
			return;
		}
		$callbacks = [
			'awfah-settings/wp-get-settings'    => [ __CLASS__, 'execute_get_settings' ],
			'awfah-settings/wp-update-settings' => [ __CLASS__, 'execute_update_settings' ],
			'awfah-settings/get-site-settings'  => [ __CLASS__, 'execute_get_site_settings' ],
		];
		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, 'manage_options' );
				},
			] ) );
		}
	}

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

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

	public static function execute_get_site_settings( $input = null ) {
		$show_on_front  = get_option( 'show_on_front' );
		$page_on_front  = get_option( 'page_on_front' );
		$page_for_posts = get_option( 'page_for_posts' );
		$permalink      = get_option( 'permalink_structure' );
		$privacy_page   = get_option( 'wp_page_for_privacy_policy' );

		return [
			'general'    => [
				'site_title'    => get_bloginfo( 'name' ),
				'site_tagline'  => get_bloginfo( 'description' ),
				'site_url'      => get_bloginfo( 'url' ),
				'admin_email'   => get_bloginfo( 'admin_email' ),
				'membership'    => get_option( 'users_can_register' ) ? 'Anyone can register' : 'Only administrators',
				'default_role'  => get_option( 'default_role' ),
				'site_language' => get_bloginfo( 'language' ),
				'timezone'      => wp_timezone_string(),
				'date_format'   => get_option( 'date_format' ),
				'time_format'   => get_option( 'time_format' ),
				'start_of_week' => get_option( 'start_of_week' ),
			],
			'reading'    => [
				'front_page_displays' => $show_on_front,
				'front_page_id'       => 'page' === $show_on_front ? (int) $page_on_front : 0,
				'posts_page_id'       => (int) $page_for_posts,
				'posts_per_page'      => get_option( 'posts_per_page' ),
				'posts_per_rss'       => get_option( 'posts_per_rss' ),
				'rss_use_excerpt'     => get_option( 'rss_use_excerpt' ),
			],
			'discussion' => [
				'default_comment_status' => get_option( 'default_comment_status' ),
				'default_ping_status'    => get_option( 'default_ping_status' ),
				'comment_moderation'     => get_option( 'comment_moderation' ),
				'require_name_email'     => get_option( 'require_name_email' ),
				'comment_registration'   => get_option( 'comment_registration' ),
				'thread_comments'        => get_option( 'thread_comments' ),
				'thread_comments_depth'  => get_option( 'thread_comments_depth' ),
				'comments_per_page'      => get_option( 'comments_per_page' ),
			],
			'media'      => [
				'thumbnail_size_w' => get_option( 'thumbnail_size_w' ),
				'thumbnail_size_h' => get_option( 'thumbnail_size_h' ),
				'medium_size_w'    => get_option( 'medium_size_w' ),
				'medium_size_h'    => get_option( 'medium_size_h' ),
				'large_size_w'     => get_option( 'large_size_w' ),
				'large_size_h'     => get_option( 'large_size_h' ),
			],
			'permalink'  => [
				'permalink_structure' => $permalink,
				'category_base'      => get_option( 'category_base' ),
				'tag_base'           => get_option( 'tag_base' ),
			],
			'privacy'    => [
				'privacy_policy_page_id'    => (int) $privacy_page,
				'privacy_policy_page_title' => $privacy_page ? get_the_title( $privacy_page ) : '',
				'blog_public'               => get_option( 'blog_public' ),
			],
			'writing'    => [
				'default_category'    => get_option( 'default_category' ),
				'default_post_format' => get_option( 'default_post_format' ),
			],
		];
	}

	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;
	}
}
