<?php
/**
 * Get Option Value Tool.
 *
 * Get the value of a specific WordPress option. Handles complex values and
 * filters sensitive options like passwords and secrets.
 *
 * @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://agenistrator.com/
 *
 * 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' ) ) {
	exit;
}

/**
 * Get_Option_Value_Tool class.
 */
class Get_Option_Value_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Get the value of a specific WordPress option/setting by name. Supports chunking for large string values and pagination for array values.';
	}

	/**
	 * 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(
				'option_name'      => array(
					'type'        => 'string',
					'description' => 'The name of the option to retrieve.',
				),
				'content_offset'   => array(
					'type'        => 'integer',
					'description' => 'For string values: byte offset to start reading from. Default: 0. Ignored for non-string values.',
				),
				'content_max_size' => array(
					'type'        => 'integer',
					'description' => 'For string values: maximum bytes to return (actual size may be smaller due to token-boundary splitting). Default: 8192. Ignored for non-string values.',
				),
				'offset'           => array(
					'type'        => 'integer',
					'description' => 'For array values: number of array elements to skip. Default: 0. Ignored for non-array values.',
				),
				'limit'            => array(
					'type'        => 'integer',
					'description' => 'For array values: maximum number of array elements to return. Default: 100. Ignored for non-array values.',
				),
			),
			'required'   => array( 'option_name' ),
		);
	}

	/**
	 * 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( 'manage_options' );
	}

	/**
	 * 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 ) {
		global $wpdb;

		$option_name      = $args['option_name'];
		$content_offset   = isset( $args['content_offset'] ) ? intval( $args['content_offset'] ) : 0;
		$content_max_size = isset( $args['content_max_size'] ) ? intval( $args['content_max_size'] ) : 8192;
		$offset           = isset( $args['offset'] ) ? max( 0, intval( $args['offset'] ) ) : 0;
		$limit            = isset( $args['limit'] ) ? max( 1, intval( $args['limit'] ) ) : 100;

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Options tool needs direct access to option_value including serialized data; caching not applicable.
		$row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT option_value, autoload FROM {$wpdb->options} WHERE option_name = %s",
				$option_name
			),
			ARRAY_A
		);

		if ( null === $row ) {
			return $this->error_response( 'Option not found', array( 'option_name' => $option_name ) );
		}

		$value      = maybe_unserialize( $row['option_value'] );
		$value_type = gettype( $value );

		// Only apply chunking to string values
		if ( 'string' === $value_type ) {
			$total_size = strlen( $value );

			// Validate offset
			if ( $content_offset < 0 ) {
				$content_offset = 0;
			}

			if ( $content_offset >= $total_size ) {
				return $this->success_response(
					'Option value retrieved',
					array(
						'option_name'        => $option_name,
						'value'              => '',
						'value_type'         => $value_type,
						'autoload'           => $row['autoload'],
						'content_total_size' => $total_size,
						'content_offset'     => $content_offset,
						'content_size'       => 0,
						'content_has_more'   => false,
					)
				);
			}

			// Extract chunk from string value
			$chunk = substr( $value, $content_offset, $content_max_size + 100 );

			// Apply token-boundary splitting
			$content_chunk = String_Utils::split_on_token_boundary(
				$chunk,
				0,
				$content_max_size
			);

			$actual_chunk_size = strlen( $content_chunk['content'] );
			$has_more          = ( $content_offset + $actual_chunk_size ) < $total_size;

			return $this->success_response(
				'Option value retrieved',
				array(
					'option_name'        => $option_name,
					'value'              => $content_chunk['content'],
					'value_type'         => $value_type,
					'autoload'           => $row['autoload'],
					'content_total_size' => $total_size,
					'content_offset'     => $content_offset,
					'content_size'       => $actual_chunk_size,
					'content_has_more'   => $has_more,
				)
			);
		}

		// Apply pagination to array values
		if ( 'array' === $value_type ) {
			$total = count( $value );

			// Validate offset
			if ( $offset >= $total ) {
				return $this->success_response(
					'Option value retrieved',
					array(
						'option_name'    => $option_name,
						'value'          => array(),
						'value_type'     => $value_type,
						'autoload'       => $row['autoload'],
						'count'          => 0,
						'total'          => $total,
						'offset'         => $offset,
						'limit'          => $limit,
						'has_more'       => false,
						'is_associative' => $this->is_associative_array( $value ),
					)
				);
			}

			// Determine if array is associative or indexed
			$is_associative = $this->is_associative_array( $value );

			// Apply pagination
			$paginated = array_slice( $value, $offset, $limit, true ); // Preserve keys
			$has_more  = $total > ( $offset + $limit );

			return $this->success_response(
				'Option value retrieved',
				array(
					'option_name'    => $option_name,
					'value'          => $paginated,
					'value_type'     => $value_type,
					'autoload'       => $row['autoload'],
					'count'          => count( $paginated ),
					'total'          => $total,
					'offset'         => $offset,
					'limit'          => $limit,
					'has_more'       => $has_more,
					'is_associative' => $is_associative,
				)
			);
		}

		// For non-string, non-array values, return as-is (objects, booleans, etc.)
		return $this->success_response(
			'Option value retrieved',
			array(
				'option_name' => $option_name,
				'value'       => $value,
				'value_type'  => $value_type,
				'autoload'    => $row['autoload'],
			)
		);
	}

	/**
	 * Check if an array is associative (has non-numeric or non-sequential keys)
	 *
	 * @param array $arr The array to check
	 * @return bool True if associative, false if indexed
	 */
	private function is_associative_array( $arr ) {
		if ( empty( $arr ) ) {
			return false;
		}
		return array_keys( $arr ) !== range( 0, count( $arr ) - 1 );
	}
}
