<?php
/**
 * List Files Tool.
 *
 * List files and directories with filtering by pattern, type, and depth.
 * Returns file metadata including size, modification time, and permissions.
 *
 * @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;
}

/**
 * List_Files_Tool class.
 */
class List_Files_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'List files and directories in a given path. Paths are relative to WordPress root unless absolute.';
	}

	/**
	 * 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(
				'path'           => array(
					'type'        => 'string',
					'description' => 'Directory path (relative to WordPress root or absolute). Use ' . DIRECTORY_SEPARATOR . ' as directory separator. Default: WordPress root.',
				),
				'recursive'      => array(
					'type'        => 'boolean',
					'description' => 'List files recursively. Default: false.',
				),
				'max_depth'      => array(
					'type'        => 'integer',
					'description' => 'Maximum recursion depth when recursive=true. Default: 3.',
				),
				'pattern'        => array(
					'type'        => 'string',
					'description' => 'Filter files by glob pattern (e.g., "*.php"). Default: all files.',
				),
				'include_hidden' => array(
					'type'        => 'boolean',
					'description' => 'Include hidden files (starting with dot). Default: false.',
				),
				'limit'          => array(
					'type'        => 'integer',
					'description' => 'Maximum number of files to return. Default: 100.',
				),
				'offset'         => array(
					'type'        => 'integer',
					'description' => 'Number of files to skip before returning results. Default: 0.',
				),
			),
			'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 is_super_admin();
	}

	/**
	 * 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 ) {
		$path           = $args['path'] ?? '.';
		$recursive      = $args['recursive'] ?? false;
		$max_depth      = $args['max_depth'] ?? 3;
		$pattern        = $args['pattern'] ?? null;
		$include_hidden = $args['include_hidden'] ?? false;
		$limit          = max( 1, $args['limit'] ?? 100 );
		$offset         = max( 0, $args['offset'] ?? 0 );

		if ( strncmp( $path, DIRECTORY_SEPARATOR, strlen( DIRECTORY_SEPARATOR ) ) !== 0 ) {
			$path = ABSPATH . $path;
		}

		// Validate path is within allowed directories
		$path = WordPress_Utils::is_allowed_path( $path );
		if ( false === $path ) {
			return $this->error_response( 'Invalid path: must be within WordPress installation or system temp directory' );
		}

		if ( ! is_dir( $path ) ) {
			return $this->error_response( 'Directory not found: ' . ( $args['path'] ?? '.' ) );
		}

		$files = $this->scan_directory( $path, $recursive, $max_depth, 0, $pattern, $include_hidden );
		$total = count( $files );

		// Apply pagination
		$paginated_files = array_slice( $files, $offset, $limit );
		$has_more        = $total > ( $offset + $limit );

		return $this->success_response(
			'Directory listed',
			array(
				'path'     => $path,
				'count'    => count( $paginated_files ),
				'total'    => $total,
				'files'    => $paginated_files,
				'limit'    => $limit,
				'offset'   => $offset,
				'has_more' => $has_more,
			)
		);
	}

	private function scan_directory( $path, $recursive, $max_depth, $current_depth, $pattern, $include_hidden ) {
		$results = array();
		$entries = scandir( $path );

		foreach ( $entries as $entry ) {
			if ( '.' === $entry || '..' === $entry ) {
				continue;
			}

			if ( ! $include_hidden && strncmp( $entry, '.', 1 ) === 0 ) {
				continue;
			}

			$full_path = $path . DIRECTORY_SEPARATOR . $entry;
			$is_dir    = is_dir( $full_path );

			if ( $pattern && ! $is_dir && ! fnmatch( $pattern, $entry ) ) {
				continue;
			}

			$item = array(
				'name'     => $entry,
				'path'     => $full_path,
				'type'     => $is_dir ? 'directory' : 'file',
				'size'     => $is_dir ? null : filesize( $full_path ),
				'modified' => gmdate( 'Y-m-d H:i:s e', filemtime( $full_path ) ),
			);

			if ( $is_dir && $recursive && $current_depth < $max_depth ) {
				$item['children'] = $this->scan_directory( $full_path, true, $max_depth, $current_depth + 1, $pattern, $include_hidden );
			}

			$results[] = $item;
		}

		return $results;
	}
}
