/**
 * Mizan Registry — Central registration for server functions.
 */

import type { RegistryEntry } from './types'

const _functions: Map<string, RegistryEntry> = new Map()

export function register(entry: RegistryEntry): void {
    if (_functions.has(entry.name) && _functions.get(entry.name)!.fn !== entry.fn) {
        throw new Error(`Function '${entry.name}' already registered`)
    }
    _functions.set(entry.name, entry)
}

export function getFunction(name: string): RegistryEntry | undefined {
    return _functions.get(name)
}

export function getAllFunctions(): Map<string, RegistryEntry> {
    return new Map(_functions)
}

export function getContextGroups(): Record<string, string[]> {
    const groups: Record<string, string[]> = {}
    for (const [name, entry] of _functions) {
        if (entry.context) {
            if (!groups[entry.context]) groups[entry.context] = []
            groups[entry.context].push(name)
        }
    }
    return groups
}

export function getContextParamNames(contextName: string): Set<string> {
    const params = new Set<string>()
    for (const [, entry] of _functions) {
        if (entry.context === contextName) {
            for (const p of entry.params) {
                params.add(p.name)
            }
        }
    }
    return params
}

export function clearRegistry(): void {
    _functions.clear()
}
