<?php
/**
 * Write File Tool.
 *
 * Write content to a file with multiple modes (overwrite, append, prepend,
 * insert, replace) and optional backup system for safe modifications.
 *
 * @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;
}

/**
 * Write_File_Tool class.
 */
class Write_File_Tool extends Abstract_File_Writer_Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Write content to a 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() . ' Paths are relative to WordPress root unless absolute. Creates file if it does not exist.';
	}

	/**
	 * 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']['file']['description'] = 'File path (relative to WordPress root or absolute). Use ' . DIRECTORY_SEPARATOR . ' as directory separator.';
		$params['properties']['create_dirs']         = array(
			'type'        => 'boolean',
			'description' => 'Create parent directories if they do not exist. Default: false.',
		);
		return $params;
	}

	/**
	 * 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 ) {
		// Check if file modifications are disabled
		if ( ! wp_is_file_mod_allowed( 'file_edit' ) ) {
			return $this->error_response( 'File modifications are disabled' );
		}

		$path        = $args['file'];
		$create_dirs = ! empty( $args['create_dirs'] );

		// Convert relative paths to absolute
		if ( strncmp( $path, DIRECTORY_SEPARATOR, strlen( DIRECTORY_SEPARATOR ) ) !== 0 ) {
			$path = ABSPATH . $path;
		}

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

		// Create parent directories if needed
		$dir = dirname( $real_path );
		if ( ! is_dir( $dir ) ) {
			if ( ! $create_dirs ) {
				return $this->error_response( "Directory does not exist: {$dir}. Set create_dirs=true to create it." );
			}
			if ( ! wp_mkdir_p( $dir ) ) {
				return $this->error_response( "Failed to create directory: {$dir}" );
			}
		}

		try {
			$data = $this->execute_mode( $real_path, $args );
		} catch ( \Throwable $e ) {
			return $this->error_response( $e->getMessage() );
		}

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