<?php
/**
 * List Theme Files Tool.
 *
 * List all files in a theme directory with recursive traversal and
 * file metadata (size, modification time).
 *
 * @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;
}

/**
 * List_Theme_Files_Tool class.
 */
class List_Theme_Files_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'List all files in a theme directory.';
	}

	/**
	 * 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(
				'theme'  => array(
					'type'        => 'string',
					'description' => 'Theme stylesheet (directory name) or theme name',
				),
				'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( 'theme' ),
		);
	}

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

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

	/**
	 * 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 ) {
		if ( ! isset( $args['theme'] ) || empty( trim( $args['theme'] ) ) ) {
			return $this->error_response( 'Theme identifier is required' );
		}

		$theme_slug = sanitize_text_field( $args['theme'] );
		$theme      = wp_get_theme( $theme_slug );

		// If not found by stylesheet, search by name
		if ( ! $theme->exists() ) {
			$all_themes = wp_get_themes();
			foreach ( $all_themes as $stylesheet => $t ) {
				if ( stripos( $t->get( 'Name' ), $theme_slug ) !== false ) {
					$theme      = $t;
					$theme_slug = $stylesheet;
					break;
				}
			}
		}

		if ( ! $theme->exists() ) {
			return $this->error_response( "Theme not found: {$theme_slug}" );
		}

		$theme_dir = $theme->get_stylesheet_directory();

		// Ensure path is within themes directory (prevent directory traversal)
		$real_theme_dir  = realpath( $theme_dir );
		$real_themes_dir = realpath( get_theme_root() );
		if ( false === $real_theme_dir || false === $real_themes_dir || ! PHP_Utils::is_path_within( $real_theme_dir, $real_themes_dir ) ) {
			return $this->error_response( 'Invalid theme path' );
		}

		$files = $this->scan_directory( $real_theme_dir, $real_theme_dir );

		// Apply pagination
		$limit     = max( 1, $args['limit'] ?? 100 );
		$offset    = max( 0, $args['offset'] ?? 0 );
		$total     = count( $files );
		$paginated = array_slice( $files, $offset, $limit );
		$has_more  = $total > ( $offset + $limit );

		return $this->success_response(
			'Theme files listed successfully',
			array(
				'theme'     => $theme_slug,
				'name'      => $theme->get( 'Name' ),
				'directory' => $theme_dir,
				'count'     => count( $paginated ),
				'total'     => $total,
				'files'     => $paginated,
				'limit'     => $limit,
				'offset'    => $offset,
				'has_more'  => $has_more,
			)
		);
	}

	/**
	 * Recursively scan directory and return file list
	 */
	private function scan_directory( $dir, $base_dir ) {
		$files = array();
		$items = scandir( $dir );

		foreach ( $items as $item ) {
			if ( '.' === $item || '..' === $item ) {
				continue;
			}

			$path          = $dir . DIRECTORY_SEPARATOR . $item;
			$relative_path = substr( $path, strlen( $base_dir ) + 1 );

			if ( is_dir( $path ) ) {
				$files[] = array(
					'path' => $relative_path,
					'type' => 'directory',
				);
				$files   = array_merge( $files, $this->scan_directory( $path, $base_dir ) );
			} else {
				$files[] = array(
					'path'     => $relative_path,
					'type'     => 'file',
					'size'     => filesize( $path ),
					'modified' => gmdate( 'Y-m-d H:i:s e', filemtime( $path ) ),
				);
			}
		}

		return $files;
	}
}
