<?php

namespace App\AI\Mcp;

use App\AI\Tools\McpTool;
use Illuminate\Support\Facades\Http;
use RuntimeException;

/**
 * A minimal MCP client speaking JSON-RPC over streamable HTTP.
 *
 * It does two things: list the server's tools, and call one of them.
 * Everything else in the agent treats those exactly like local tools.
 */
class Client
{
    protected ?string $sessionId = null;

    /** @var array<int, McpTool>|null */
    protected ?array $tools = null;

    protected int $id = 0;

    public function __construct(
        protected string $url,
        protected string $token,
    ) {}

    /**
     * Every tool the server exposes, wrapped so the agent can use them.
     *
     * @return array<int, McpTool>
     */
    public function tools(): array
    {
        return $this->tools ??= array_map(
            fn (array $tool) => new McpTool(
                client: $this,
                name: $tool['name'],
                description: $tool['description'] ?? '',
                inputSchema: $tool['inputSchema'] ?? ['type' => 'object', 'properties' => (object) []],
            ),
            $this->rpc('tools/list')['tools'] ?? []
        );
    }

    /**
     * Invoke a tool and flatten its content blocks into a string.
     */
    public function call(string $name, array $arguments): string
    {
        $result = $this->rpc('tools/call', [
            'name' => $name,
            'arguments' => (object) $arguments,
        ]);

        $text = collect($result['content'] ?? [])
            ->map(fn (array $block) => $block['text'] ?? json_encode($block))
            ->implode("\n");

        return ($result['isError'] ?? false)
            ? "Tool error: {$text}"
            : $text;
    }

    protected function rpc(string $method, array $params = []): array
    {
        $this->sessionId ?? $this->initialize();

        $payload = $this->send($method, $params);

        if (isset($payload['error'])) {
            throw new RuntimeException("MCP {$method} failed: ".json_encode($payload['error']));
        }

        return $payload['result'] ?? [];
    }

    protected function initialize(): void
    {
        $response = $this->post('initialize', [
            'protocolVersion' => '2025-06-18',
            'capabilities' => (object) [],
            'clientInfo' => ['name' => 'aia', 'version' => '1.0'],
        ]);

        $this->sessionId = $response->header('Mcp-Session-Id') ?: null;
    }

    protected function send(string $method, array $params): array
    {
        return $this->decode($this->post($method, $params)->body());
    }

    protected function post(string $method, array $params)
    {
        return Http::timeout(180)
            ->withToken($this->token)
            ->withHeaders(array_filter([
                'Accept' => 'application/json, text/event-stream',
                'Mcp-Session-Id' => $this->sessionId,
            ]))
            ->post($this->url, [
                'jsonrpc' => '2.0',
                'id' => ++$this->id,
                'method' => $method,
                'params' => (object) $params,
            ])
            ->throw();
    }

    /**
     * Responses arrive SSE-framed ("data: {...}"), so pull the JSON back out.
     */
    protected function decode(string $body): array
    {
        foreach (explode("\n", $body) as $line) {
            $line = trim($line);

            if ($line === '') {
                continue;
            }

            if (str_starts_with($line, 'data:')) {
                $line = trim(substr($line, 5));
            }

            $decoded = json_decode($line, true);

            if (is_array($decoded) && (isset($decoded['result']) || isset($decoded['error']))) {
                return $decoded;
            }
        }

        throw new RuntimeException('Unparseable MCP response: '.substr($body, 0, 300));
    }
}
