/**
 * Dynamic resource: document tree as navigable JSON.
 */
import { toPlain } from '@abraca/dabra'
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { AbracadabraMCPServer } from '../server.ts'
import type { TreeEntry } from '../converters/types.ts'

function readEntries(treeMap: any): TreeEntry[] {
  const entries: TreeEntry[] = []
  treeMap.forEach((raw: any, id: string) => {
    // Entries are nested Y.Map values — raw field access returns undefined;
    // resolve via toPlain first (mirrors tree.ts:readEntries).
    const value = toPlain(raw) as any
    if (typeof value !== 'object' || value === null) return // skip non-entry keys (e.g. ":updatedAt")
    entries.push({
      id,
      label: value.label || 'Untitled',
      parentId: value.parentId ?? null,
      order: value.order ?? 0,
      type: value.type,
      meta: value.meta,
    })
  })
  return entries
}

function childrenOf(entries: TreeEntry[], parentId: string | null): TreeEntry[] {
  return entries
    .filter(e => e.parentId === parentId)
    .sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
}

function buildTree(entries: TreeEntry[], rootId: string | null, maxDepth: number, depth = 0): any[] {
  if (maxDepth >= 0 && depth >= maxDepth) return []
  return childrenOf(entries, rootId).map(e => ({
    id: e.id,
    label: e.label,
    type: e.type,
    children: buildTree(entries, e.id, maxDepth, depth + 1),
  }))
}

export function registerTreeResource(mcp: McpServer, server: AbracadabraMCPServer) {
  mcp.resource(
    'tree',
    'abracadabra://tree',
    {
      description: 'Full document tree as nested JSON. Shows the complete hierarchy of all documents.',
      mimeType: 'application/json',
    },
    async () => {
      const treeMap = server.getTreeMap()
      if (!treeMap) {
        return {
          contents: [{
            uri: 'abracadabra://tree',
            text: '{"error": "Not connected"}',
            mimeType: 'application/json',
          }],
        }
      }

      const entries = readEntries(treeMap)
      const tree = buildTree(entries, null, 10)

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