<?php

/**
 * A radix-trie based URI router. Seperates URIs into chunks, then turns those chunks into an efficiently parsed
 * trie. Supports URI variables!
 */
class Router
{
	/**
	 * List of valid HTTP verbs.
	 */
	private const VALID_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];

	/**
	 * The tree of currently registered routes.
	 */
	private array $routes = [];

	/**
	 * Store the last inserted node so we can register middleware and attributes to it.
	 */
	private array $last_inserted_node;

	/**
	 * Add a route to the route tree. The route must be a URI path, and contain dynamic segments
	 * using a colon prefix. (:id, :slug, etc)
	 *
	 * Example:
	 * `$r->add($routes, 'GET', '/posts/:id', function($id) { echo "Viewing post $id"; });`
	 */
	public function add(string $method, string $route, callable $handler): Router
	{
		$this->validateMethod($method);
		$this->validateRoute($route);

		// Expand the route into segments and make dynamic segments into a common placeholder
		$segments = array_map(function($segment) {
			return str_starts_with($segment, ':') ? ':x' : $segment;
		}, explode('/', trim($route, '/')));

		// Push each segment into the routes array as a node, except if this is the root node
		$node = &$this->routes;
		foreach ($segments as $segment) {
			// skip an empty segment, which allows us to register handlers for the root node
			if ($segment === '') continue;
			$node = &$node[$segment]; // build the node tree as we go
		}

		// Add the handler to the last node
		$node[$method] = ['handler' => $handler, 'middleware' => []];

		// Store a reference to the node so we can add middleware to it.
		$this->last_inserted_node = &$node[$method];

		return $this;
	}

	/**
	 * Perform a lookup in the route tree for a given method and URI. Returns an array with a result code,
	 * a handler if found, and any dynamic parameters. Codes are 200 for success, 404 for not found, and
	 * 405 for method not allowed.
	 *
	 * @return array ['code', 'handler', 'params']
	 */
	public function lookup(string $method, string $uri): array
	{
		// node is a reference to our current location in the node tree
		$node = $this->routes;

		// params will hold any dynamic segments we find
		$params = [];

		// if the URI is just a slash, we can return the handler for the root node
		if ($uri === '/') {
			return isset($node[$method])
				? ['code' => 200, 'handler' => $node[$method]['handler']]
				: ['code' => 405];
		}

		// We'll split up the URI into segments and traverse the node tree
		foreach (explode('/', trim($uri, '/')) as $segment) {
			// if there is a node for this segment, move to it
			if (isset($node[$segment])) {
				$node = $node[$segment];
				continue;
			}

			// if there is a dynamic segment, move to it and store the value
			if (isset($node[':x'])) {
				$params[] = $segment;
				$node = $node[':x'];
				continue;
			}

			// if we can't find a node for this segment, return 404
			return ['code' => 404];
		}

		// if we found a handler for the method, return it and any params. if not, return a 405
		return isset($node[$method])
			? ['code' => 200, 'handler' => $node[$method]['handler'], 'params' => $params ?? [], 'middleware' => $node[$method]['middleware']]
			: ['code' => 405];
	}

	/**
	 * Add a middleware function to the last inserted node's stack.
	 */
	public function middleware(callable $middleware): Router
	{
		$this->last_inserted_node['middleware'][] = $middleware;
		return $this;
	}

	/**
	 * Shorthand to register a GET route.
	 */
	public function get(string $route, callable $handler): Router
	{
		return $this->add('GET', $route, $handler);
	}

	/**
	 * Shorthand to register a POST route.
	 */
	public function post(string $route, callable $handler): Router
	{
		return $this->add('POST', $route, $handler);
	}

	/**
	 * Shorthand to register a PUT route.
	 */
	public function put(string $route, callable $handler): Router
	{
		return $this->add('PUT', $route, $handler);
	}

	/**
	 * Shorthand to register a DELETE route.
	 */
	public function delete(string $route, callable $handler): Router
	{
		return $this->add('DELETE', $route, $handler);
	}

	/**
	 * Shorthand to register a PATCH route.
	 */
	public function patch(string $route, callable $handler): Router
	{
		return $this->add('PATCH', $route, $handler);
	}

	/**
	 * Validate the given method against valid HTTP verbs.
	 */
	private function validateMethod(string $method): void
    {
        if (!in_array($method, self::VALID_METHODS)) {
            throw new InvalidArgumentException("Invalid HTTP method: $method");
        }
    }

	/**
	 * Validate that a new route follows expected formatting.
	 */
	private function validateRoute(string $route): void
	{
		if ($route === '') {
			throw new InvalidArgumentException("Route cannot be empty");
		}

		// Ensure route starts with a slash
		if (!str_starts_with($route, '/')) {
			throw new InvalidArgumentException("Route must start with a '/'");
		}

		// Optional: Check for consecutive dynamic segments or invalid characters
		if (preg_match('/(:x.*){2,}/', $route)) {
			throw new InvalidArgumentException("Invalid route pattern: consecutive dynamic segments");
		}
	}
}
