/**
 * Dynamic resource: server health + info.
 */
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { AbracadabraMCPServer } from '../server.ts'

export function registerServerInfoResource(mcp: McpServer, server: AbracadabraMCPServer) {
  mcp.resource(
    'server-info',
    'abracadabra://server-info',
    {
      description: 'Abracadabra server info: name, version, root document ID, and health status.',
      mimeType: 'application/json',
    },
    async () => {
      let health = null
      try {
        health = await server.client.health()
      } catch {
        // health endpoint unavailable
      }

      const spaces = server.spaces
      const activeSpace = spaces.find(s => s.id === server.rootDocId) ?? null

      const info = {
        serverInfo: server.serverInfo,
        activeSpaceDocId: server.rootDocId,
        activeSpace,
        spaces: spaces.length > 0 ? spaces : undefined,
        health,
        agent: {
          name: server.agentName,
          color: server.agentColor,
        },
      }

      return {
        contents: [{
          uri: 'abracadabra://server-info',
          text: JSON.stringify(info, null, 2),
          mimeType: 'application/json',
        }],
      }
    }
  )
}
