<?php
/**
 * Configure LLM Provider Tool.
 *
 * Add or update LLM provider configurations including API keys and custom
 * endpoints. Supports Anthropic, OpenAI, and OpenRouter providers.
 *
 * @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;
}

/**
 * Configure_LLM_Provider_Tool class.
 */
class Configure_LLM_Provider_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		$types = implode( ', ', Provider_Manager::get_instance()->get_provider_types() );
		return "Add or update an LLM provider configuration. Supported types: {$types}.";
	}

	/**
	 * Get additional description instructions for the LLM.
	 *
	 * @return string Additional instructions appended to description.
	 * @since     1.0.0
	 */
	public function get_description_instructions() {
		return "Use `list_options` with search query '%agenistrator%' to see existing provider configurations.";
	}

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

	/**
	 * 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(
				'provider_id'   => array(
					'type'        => 'string',
					'description' => 'Existing provider ID to update. Leave empty to create new provider.',
				),
				'provider_type' => array(
					'type'        => 'string',
					'description' => 'Provider type (e.g., OpenAI, Anthropic). Required when creating new provider.',
				),
				'display_name'  => array(
					'type'        => 'string',
					'description' => 'Display name for the provider. Required when creating new provider.',
				),
				'api_key'       => array(
					'type'        => 'string',
					'description' => 'API key for the provider.',
				),
				'enabled'       => array(
					'type'        => 'boolean',
					'description' => 'Whether the provider is enabled. Default: true.',
				),
			),
			'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 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 ) {
		$provider_manager = Provider_Manager::get_instance();
		$provider_id      = $args['provider_id'] ?? '';

		if ( ! empty( $provider_id ) ) {
			return $this->update_existing_provider( $provider_manager, $provider_id, $args );
		}

		return $this->create_new_provider( $provider_manager, $args );
	}

	private function create_new_provider( $provider_manager, $args ) {
		$provider_type = $args['provider_type'] ?? '';
		$display_name  = $args['display_name'] ?? '';

		if ( empty( $provider_type ) ) {
			return $this->error_response( 'provider_type is required when creating a new provider' );
		}
		if ( empty( $display_name ) ) {
			return $this->error_response( 'display_name is required when creating a new provider' );
		}

		$valid_types = $provider_manager->get_provider_types();
		if ( ! in_array( $provider_type, $valid_types, true ) ) {
			return $this->error_response( 'Invalid provider_type. Must be one of: ' . implode( ', ', $valid_types ) );
		}

		$parameters = array();
		if ( ! empty( $args['api_key'] ) ) {
			$parameters['api_key'] = $args['api_key'];
		}

		try {
			$new_id = $provider_manager->create_provider( $provider_type, $display_name, $parameters );

			return $this->success_response(
				'Provider created',
				array(
					'provider_id'   => $new_id,
					'provider_type' => $provider_type,
					'display_name'  => $display_name,
					'enabled'       => true,
				)
			);
		} catch ( \Throwable $e ) {
			return $this->error_response( 'Failed to create provider: ' . $e->getMessage() );
		}
	}

	private function update_existing_provider( $provider_manager, $provider_id, $args ) {
		try {
			$provider = $provider_manager->get_provider( $provider_id );
		} catch ( \Throwable $e ) {
			return $this->error_response( "Provider not found: {$provider_id}" );
		}

		$display_name = $args['display_name'] ?? $provider->get_display_name();
		$parameters   = $provider->get_params();

		if ( ! empty( $args['api_key'] ) ) {
			$parameters['api_key'] = $args['api_key'];
		}

		$provider_manager->update_provider( $provider_id, $display_name, $parameters );

		if ( isset( $args['enabled'] ) ) {
			if ( $args['enabled'] ) {
				$provider_manager->enable_provider( $provider_id );
			} else {
				$provider_manager->disable_provider( $provider_id );
			}
		}

		return $this->success_response(
			'Provider updated',
			array(
				'provider_id'  => $provider_id,
				'display_name' => $display_name,
				'enabled'      => $args['enabled'] ?? $provider_manager->is_provider_enabled( $provider_id ),
			)
		);
	}
}
