<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Niwa_AI_MCP_Server {

	const REST_NAMESPACE   = 'niwa-ai/v1';
	const PROTOCOL_VERSION = '2024-11-05';
	const SERVER_NAME      = 'niwa-ai-mcp';

	private $auth;
	private $bridge;
	private $token_claims = array();

	public function __construct( Niwa_AI_MCP_JWT_Auth $auth, Niwa_AI_MCP_Tools_Bridge $bridge ) {
		$this->auth   = $auth;
		$this->bridge = $bridge;
	}

	public function authenticate_mcp_request( WP_REST_Request $request ) {
		$token = $request->get_header( 'X-Niwa-MCP-Token' );

		if ( empty( $token ) ) {
			return new WP_Error(
				'niwa_mcp_no_token',
				__( 'MCP token required.', 'niwa-ai' ),
				array( 'status' => 401 )
			);
		}

		$result = $this->auth->verify_token( $token );

		if ( is_wp_error( $result ) ) {
			return new WP_Error(
				$result->get_error_code(),
				$result->get_error_message(),
				array( 'status' => 403 )
			);
		}

		// Set authenticated user.
		wp_set_current_user( intval( $result['user_id'] ) );
		$this->token_claims = $result;

		return true;
	}

	/* ================================================================
	 * MCP Protocol Handler (JSON-RPC 2.0)
	 * ============================================================= */

	public function handle_mcp_request( WP_REST_Request $request ) {
		$authenticated = $this->authenticate_mcp_request( $request );
		if ( is_wp_error( $authenticated ) ) {
			return $authenticated;
		}
		$body = $request->get_json_params();

		// Validate JSON-RPC envelope.
		$jsonrpc = isset( $body['jsonrpc'] ) ? (string) $body['jsonrpc'] : '';
		$method  = isset( $body['method'] ) ? (string) $body['method'] : '';
		$params  = isset( $body['params'] ) && is_array( $body['params'] ) ? $body['params'] : array();
		$id      = isset( $body['id'] ) ? $body['id'] : null;

		if ( '2.0' !== $jsonrpc ) {
			return rest_ensure_response(
				$this->jsonrpc_error( $id, -32600, 'Invalid JSON-RPC version. Expected 2.0.' )
			);
		}

		if ( '' === $method ) {
			return rest_ensure_response(
				$this->jsonrpc_error( $id, -32600, 'Method is required.' )
			);
		}

		// Notifications (no id) - return 204 No Content.
		if ( null === $id ) {
			return new WP_REST_Response( null, 204 );
		}

		// Dispatch by method.
		switch ( $method ) {
			case 'initialize':
				return rest_ensure_response( $this->handle_initialize( $id ) );

			case 'tools/list':
				return rest_ensure_response( $this->handle_tools_list( $params, $id ) );

			case 'tools/call':
				return rest_ensure_response( $this->handle_tools_call( $params, $id ) );

			case 'resources/list':
				return rest_ensure_response( $this->handle_resources_list( $id ) );

			case 'resources/read':
				return rest_ensure_response( $this->handle_resources_read( $params, $id ) );

			case 'ping':
				return rest_ensure_response( $this->jsonrpc_success( $id, new stdClass() ) );

			default:
				return rest_ensure_response(
					$this->jsonrpc_error( $id, -32601, 'Method not found: ' . $method )
				);
		}
	}

	/* ================================================================
	 * JSON-RPC Method Handlers
	 * ============================================================= */

	private function handle_initialize( $id ) {
		return $this->jsonrpc_success(
			$id,
			array(
				'protocolVersion' => self::PROTOCOL_VERSION,
				'capabilities'    => array(
					'tools'     => array( 'listChanged' => false ),
					'resources' => array(
						'subscribe'   => false,
						'listChanged' => false,
					),
				),
				'serverInfo'      => array(
					'name'    => self::SERVER_NAME,
					'version' => defined( 'NIWA_AI_VERSION' ) ? NIWA_AI_VERSION : '1.0.0',
				),
			)
		);
	}

	private function handle_tools_list( $params, $id ) {
		$tools = $this->bridge->get_mcp_tool_list();
		if ( ! $this->has_scope( 'read_options' ) ) {
			$tools = array_values(
				array_filter(
					$tools,
					static function ( $tool ) {
						return 'wp_option_get' !== (string) ( $tool['name'] ?? '' );
					}
				)
			);
		}

		// Support cursor-based pagination (optional).
		// For now, return all tools (no pagination needed for ~67 tools).

		return $this->jsonrpc_success( $id, array( 'tools' => $tools ) );
	}

	private function handle_tools_call( $params, $id ) {
		$tool_name = isset( $params['name'] ) ? (string) $params['name'] : '';
		$arguments = isset( $params['arguments'] ) && is_array( $params['arguments'] )
			? $params['arguments']
			: array();

		if ( '' === $tool_name ) {
			return $this->jsonrpc_error( $id, -32602, 'Tool name is required.' );
		}
		if ( 'wp_option_get' === $tool_name && ! $this->has_scope( 'read_options' ) ) {
			return $this->jsonrpc_error( $id, -32603, 'MCP token requires the read_options scope for wp_option_get.' );
		}

		// Verify user has admin capabilities for write operations.
		if ( ! $this->bridge->is_read_only_tool( $tool_name ) && ! current_user_can( 'manage_options' ) ) {
			return $this->jsonrpc_error(
				$id,
				-32603,
				'Insufficient permissions for write operation: ' . $tool_name
			);
		}

		$result = $this->bridge->call_tool( $tool_name, $arguments );

		return $this->jsonrpc_success( $id, $result );
	}

	private function handle_resources_list( $id ) {
		return $this->jsonrpc_success(
			$id,
			array(
				'resources' => array(
					array(
						'uri'         => 'niwa://site-info',
						'name'        => 'Site Information',
						'description' => 'WordPress site metadata, configuration, active plugins, theme, and content statistics.',
						'mimeType'    => 'application/json',
					),
				),
			)
		);
	}

	private function handle_resources_read( $params, $id ) {
		$uri = isset( $params['uri'] ) ? (string) $params['uri'] : '';

		if ( 'niwa://site-info' === $uri ) {
			$info = array(
				'site_name'         => get_bloginfo( 'name' ),
				'site_url'          => get_site_url(),
				'site_description'  => get_bloginfo( 'description' ),
				'admin_email'       => get_bloginfo( 'admin_email' ),
				'wordpress_version' => get_bloginfo( 'version' ),
				'php_version'       => phpversion(),
				'language'          => get_bloginfo( 'language' ),
				'timezone'          => wp_timezone_string(),
				'is_multisite'      => is_multisite(),
				'woocommerce'       => class_exists( 'WooCommerce' ) ? WC()->version : false,
				'niwa_ai_version'   => defined( 'NIWA_AI_VERSION' ) ? NIWA_AI_VERSION : 'unknown',
				'active_theme'      => wp_get_theme()->get( 'Name' ),
			);

			return $this->jsonrpc_success(
				$id,
				array(
					'contents' => array(
						array(
							'uri'      => $uri,
							'mimeType' => 'application/json',
							'text'     => wp_json_encode( $info, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT ),
						),
					),
				)
			);
		}

		return $this->jsonrpc_error( $id, -32602, 'Unknown resource URI: ' . $uri );
	}

	private function has_scope( $scope ) {
		return in_array( (string) $scope, (array) ( $this->token_claims['scopes'] ?? array() ), true );
	}

	/* ================================================================
	 * JSON-RPC Helpers
	 * ============================================================= */

	private function jsonrpc_success( $id, $result ) {
		return array(
			'jsonrpc' => '2.0',
			'id'      => $id,
			'result'  => $result,
		);
	}

	private function jsonrpc_error( $id, $code, $message, $data = null ) {
		$error = array(
			'code'    => $code,
			'message' => $message,
		);

		if ( null !== $data ) {
			$error['data'] = $data;
		}

		return array(
			'jsonrpc' => '2.0',
			'id'      => $id,
			'error'   => $error,
		);
	}
}
