<?php

namespace AtlasAiDev\Awfah\Abilities;

use WP_Error;

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

class Site_Info_Abilities {

	public static function get_abilities(): array {
		return [
			[
				'id'           => 'awfah-site/get-site-info',
				'module'       => 'site_info',
				'label'        => __( 'Get Site Info', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Provides detailed information about the WordPress site including site details, plugins, themes, and users.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-site',
				'input_schema' => [ 'type' => 'object', 'properties' => (object) [] ],
				'meta'         => [
					'show_in_rest' => true,
					'mcp'          => [ 'public' => true ],
					'uri'          => 'wordpress://ai-agent-hub/site/info',
					'mimeType'     => 'application/json',
				],
			],
			[
				'id'           => 'awfah-site/get-plugin-info',
				'module'       => 'site_info',
				'label'        => __( 'Get Plugin Info', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Provides detailed information about active WordPress plugins.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-site',
				'input_schema' => [ 'type' => 'object', 'properties' => (object) [] ],
				'meta'         => [
					'show_in_rest' => true,
					'mcp'          => [ 'public' => true ],
					'uri'          => 'wordpress://ai-agent-hub/site/plugins',
					'mimeType'     => 'application/json',
				],
			],
			[
				'id'           => 'awfah-site/get-theme-info',
				'module'       => 'site_info',
				'label'        => __( 'Get Theme Info', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Provides detailed information about the active WordPress theme.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-site',
				'input_schema' => [ 'type' => 'object', 'properties' => (object) [] ],
				'meta'         => [
					'show_in_rest' => true,
					'mcp'          => [ 'public' => true ],
					'uri'          => 'wordpress://ai-agent-hub/site/theme',
					'mimeType'     => 'application/json',
				],
			],
			[
				'id'           => 'awfah-site/get-user-info',
				'module'       => 'site_info',
				'label'        => __( 'Get User Info', 'ai-workflow-automation-ai-agent-hub' ),
				'description'  => __( 'Provides information about registered WordPress users and their roles.', 'ai-workflow-automation-ai-agent-hub' ),
				'category'     => 'awfah-site',
				'input_schema' => [ 'type' => 'object', 'properties' => (object) [] ],
				'meta'         => [
					'show_in_rest' => true,
					'mcp'          => [ 'public' => true ],
					'uri'          => 'wordpress://ai-agent-hub/site/users',
					'mimeType'     => 'application/json',
				],
			],
		];
	}

	public static function register(): void {
		if ( ! function_exists( 'wp_register_ability' ) ) {
			return;
		}
		$callbacks = [
			'awfah-site/get-site-info'   => [ __CLASS__, 'execute_get_site_info' ],
			'awfah-site/get-plugin-info' => [ __CLASS__, 'execute_get_plugin_info' ],
			'awfah-site/get-theme-info'  => [ __CLASS__, 'execute_get_theme_info' ],
			'awfah-site/get-user-info'   => [ __CLASS__, 'execute_get_user_info' ],
		];
		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_site_info( $input = null ) {
		if ( ! function_exists( 'get_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		$users = get_users();
		return [
			'site_name'         => get_bloginfo( 'name' ),
			'site_url'          => get_bloginfo( 'url' ),
			'site_description'  => get_bloginfo( 'description' ),
			'site_admin_email'  => get_bloginfo( 'admin_email' ),
			'wordpress_version' => get_bloginfo( 'version' ),
			'language'          => get_bloginfo( 'language' ),
			'timezone'          => wp_timezone_string(),
			'active_plugins'    => get_option( 'active_plugins' ),
			'all_plugins'       => get_plugins(),
			'active_theme'      => wp_get_theme()->get( 'Name' ),
			'all_themes'        => array_keys( wp_get_themes() ),
			'users_count'       => count( $users ),
			'users_roles'       => array_count_values( array_map( function ( $u ) {
				return $u->roles[0] ?? 'none';
			}, $users ) ),
		];
	}

	public static function execute_get_plugin_info( $input = null ) {
		if ( ! function_exists( 'get_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		$all_plugins    = get_plugins();
		$active_plugins = get_option( 'active_plugins', [] );
		$result         = [];
		foreach ( $all_plugins as $path => $data ) {
			$result[] = [
				'name'        => $data['Name'] ?? '',
				'version'     => $data['Version'] ?? '',
				'author'      => $data['Author'] ?? '',
				'description' => $data['Description'] ?? '',
				'active'      => in_array( $path, $active_plugins, true ),
				'path'        => $path,
			];
		}
		return $result;
	}

	public static function execute_get_theme_info( $input = null ) {
		$theme  = wp_get_theme();
		$result = [
			'name'        => $theme->get( 'Name' ),
			'version'     => $theme->get( 'Version' ),
			'author'      => $theme->get( 'Author' ),
			'description' => $theme->get( 'Description' ),
			'template'    => $theme->get_template(),
			'stylesheet'  => $theme->get_stylesheet(),
			'is_child'    => $theme->parent() ? true : false,
		];
		if ( $theme->parent() ) {
			$parent            = $theme->parent();
			$result['parent'] = [
				'name'    => $parent->get( 'Name' ),
				'version' => $parent->get( 'Version' ),
			];
		}
		return $result;
	}

	public static function execute_get_user_info( $input = null ) {
		$users = get_users();
		$roles = [];
		foreach ( $users as $user ) {
			$role = $user->roles[0] ?? 'none';
			if ( ! isset( $roles[ $role ] ) ) {
				$roles[ $role ] = 0;
			}
			++$roles[ $role ];
		}
		return [
			'total' => count( $users ),
			'roles' => $roles,
			'users' => array_map( function ( $u ) {
				return [
					'id'           => $u->ID,
					'login'        => $u->user_login,
					'display_name' => $u->display_name,
					'email'        => $u->user_email,
					'roles'        => $u->roles,
					'registered'   => $u->user_registered,
				];
			}, $users ),
		];
	}
}
