<?php
/**
 * Get Site Health Tool.
 *
 * Get WordPress Site Health diagnostics information using WP_Site_Health class.
 * Returns test results, status indicators, and recommendations.
 *
 * @package   Agenistrator
 * @since     1.0.0
 * @author    Alex Ruban <alex@maximum.guru>
 * @author    Maximum Software Inc <contact@maximum.software>
 * @license   GPL-3.0-only
 * @link      https://maximum.software/
 *
 * SPDX-FileCopyrightText: 2025-2026 Alex Ruban <alex@maximum.guru>
 * SPDX-FileCopyrightText: 2025-2026 Maximum Software Inc <contact@maximum.software>
 * SPDX-License-Identifier: GPL-3.0-only
 */

namespace Agenistrator;

// Direct access prevention
if ( ! defined( 'ABSPATH' ) ) {
	return;
}

/**
 * Get_Site_Health_Tool class.
 */
class Get_Site_Health_Tool extends Tool {

	/**
	 * Get the tool ID.
	 *
	 * @return string The tool ID.
	 * @since     1.0.0
	 */
	public function get_id() {
		return 'get_site_health';
	}

	/**
	 * Get the tool name.
	 *
	 * @return string The tool name.
	 * @since     1.0.0
	 */
	public function get_name() {
		return __( 'Get Site Health', 'agenistrator' );
	}

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Get WordPress Site Health diagnostics information including tests results and debug data.';
	}

	/**
	 * Check if this tool is read-only.
	 *
	 * @return bool True if the tool only reads data.
	 * @since     1.0.0
	 */
	public function is_read_only() {
		return true;
	}

	/**
	 * Get the parameters schema for this tool.
	 *
	 * @return array Parameters schema in JSON Schema format.
	 * @since     1.0.0
	 */
	public function get_parameters() {
		return array(
			'type'       => 'object',
			'properties' => array(
				'include_debug_data' => array(
					'type'        => 'boolean',
					'description' => 'Include detailed debug data in the response. Default: false.',
				),
			),
			'required'   => array(),
		);
	}

	/**
	 * Get the default enabled status for this tool.
	 *
	 * @return bool True if enabled by default, false otherwise.
	 * @since     1.0.0
	 */
	public function get_default_enabled_status() {
		return true;
	}

	/**
	 * Check if the current user can execute this tool.
	 *
	 * @return bool True if the current user has permission.
	 * @since     1.0.0
	 */
	public function current_user_can_execute() {
		return current_user_can( 'view_site_health_checks' );
	}

	/**
	 * Execute the tool with the given arguments.
	 *
	 * @param array $args The tool arguments.
	 *
	 * @return array The tool execution result.
	 * @since     1.0.0
	 */
	protected function execute( $args ) {
		$include_debug = $args['include_debug_data'] ?? false;

		if ( ! class_exists( 'WP_Site_Health' ) ) {
			require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php';
		}

		\WP_Site_Health::get_instance();
		$tests   = \WP_Site_Health::get_tests();
		$results = array(
			'critical'    => array(),
			'recommended' => array(),
			'good'        => array(),
		);

		foreach ( array( 'direct', 'async' ) as $type ) {
			if ( empty( $tests[ $type ] ) ) {
				continue;
			}
			foreach ( $tests[ $type ] as $test_key => $test ) {
				if ( 'direct' === $type && is_callable( $test['test'] ) ) {
					$result = call_user_func( $test['test'] );
					if ( is_array( $result ) && isset( $result['status'] ) ) {
						$category               = 'critical' === $result['status'] ? 'critical' :
							( 'recommended' === $result['status'] ? 'recommended' : 'good' );
						$results[ $category ][] = array(
							'test'        => $test_key,
							'label'       => $result['label'] ?? $test_key,
							'status'      => $result['status'],
							'description' => wp_strip_all_tags( $result['description'] ?? '' ),
						);
					}
				}
			}
		}

		$response = array(
			'summary' => array(
				'critical_count'    => count( $results['critical'] ),
				'recommended_count' => count( $results['recommended'] ),
				'good_count'        => count( $results['good'] ),
			),
			'tests'   => $results,
		);

		if ( $include_debug ) {
			if ( ! class_exists( 'WP_Debug_Data' ) ) {
				require_once ABSPATH . 'wp-admin/includes/class-wp-debug-data.php';
			}
			\WP_Debug_Data::check_for_updates();
			$debug_data = \WP_Debug_Data::debug_data();

			$response['debug_data'] = array();
			foreach ( $debug_data as $section_key => $section ) {
				$fields = array();
				foreach ( $section['fields'] as $field_key => $field ) {
					$fields[ $field_key ] = array(
						'label' => $field['label'],
						'value' => $field['value'],
						'debug' => $field['debug'] ?? null,
					);
				}
				$response['debug_data'][ $section_key ] = array(
					'label'  => $section['label'],
					'fields' => $fields,
				);
			}
		}

		return $this->success_response( 'Site health retrieved', $response );
	}
}
