<?php
/**
 * Read Theme File Tool.
 *
 * Read the contents of a theme file using line/byte/search modes.
 * Extends Abstract_File_Reader_Tool for memory-efficient large file operations.
 *
 * @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;
}

/**
 * Read_Theme_File_Tool class.
 */
class Read_Theme_File_Tool extends Abstract_File_Reader_Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Read a theme file.';
	}

	/**
	 * Get usage instructions for the LLM.
	 *
	 * @return string Instructions for using this tool.
	 * @since     1.0.0
	 */
	public function get_instructions() {
		return parent::get_instructions() . ' File path is relative to the 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() {
		$params               = parent::get_parameters();
		$params['properties'] = array_merge(
			array(
				'theme' => array(
					'type'        => 'string',
					'description' => 'Theme stylesheet (directory name) or theme name',
				),
			),
			$params['properties']
		);
		$params['required'][] = 'theme';
		return $params;
	}

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

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

		$theme_slug = trim( $args['theme'] );
		$file       = $args['file'];

		$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();
		$file_path = $theme_dir . DIRECTORY_SEPARATOR . $file;

		// Validate file path is within theme directory (prevent directory traversal)
		$real_file_path = realpath( $file_path );
		$real_theme_dir = realpath( $theme_dir );
		if ( false === $real_file_path || false === $real_theme_dir || ! PHP_Utils::is_path_within( $real_file_path, $real_theme_dir ) ) {
			return $this->error_response( 'Invalid file path or file does not exist' );
		}

		if ( ! is_file( $real_file_path ) ) {
			return $this->error_response( 'File not found' );
		}

		try {
			$data = $this->execute_mode(
				$real_file_path,
				$args,
				array(
					'theme'     => $theme_slug,
					'file'      => $file,
					'extension' => pathinfo( $real_file_path, PATHINFO_EXTENSION ),
					'modified'  => gmdate( 'Y-m-d H:i:s e', filemtime( $real_file_path ) ),
				)
			);
		} catch ( \Throwable $e ) {
			return $this->error_response( $e->getMessage() );
		}

		return $this->success_response( 'File read', $data );
	}
}
