/**
 * In-plugin MCP host. Connects every enabled server from config.servers over
 * stdio or streamable-http, discovers tools, filters them through the role
 * preset, and registers the survivors on ctx.tools as \`mcp__<server>__<rawName>\`.
 */

import { createHash } from 'node:crypto'
import { setDefaultResultOrder } from 'node:dns'
import { existsSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
import { ListToolsResultSchema } from '@modelcontextprotocol/sdk/types.js'
import z from 'zod'
import type { Context } from '@deepseek-ai/cordis'
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
import type { RezConfig, RezMcpTransport, RezRoleId, RezServerId, RezServerStatus, RezTestResult } from './protocol.ts'
import { isToolAllowed } from './presets.ts'
import { estimateTokens, type TokenManager } from './token-manager.ts'

const MAX_PUBLIC_NAME_LENGTH = 64
const INVALID_NAME_CHARS = /[^A-Za-z0-9_-]/g
const HASH_LENGTH = 12

const RawCallToolResultSchema = z.record(z.string(), z.unknown())

interface McpToolInfo {
  rawName: string
  description: string
  inputSchema: Record<string, unknown>
}

interface ServerDescriptor {
  id: RezServerId
  serverName: string
  transport: RezMcpTransport
  command?: string
  args?: string[]
  env?: Record<string, string>
  cwd?: string
  url?: string
  headers?: Record<string, string>
  toolCallTimeoutMs: number
}

interface LiveConnection {
  descriptor: ServerDescriptor
  client: Client
  transport: StdioClientTransport | StreamableHTTPClientTransport
  tools: McpToolInfo[]
  disposers: Map<string, () => void>
  startedAt: number
  lastError?: string
}

/** Copy of dsh-mcp-client's deterministic public-name derivation. */
function publicToolName(serverName: string, rawName: string): string {
  const joined = 'mcp__' + serverName + '__' + rawName
  const normalized = joined.replace(INVALID_NAME_CHARS, '_')
  if (normalized === joined && normalized.length <= MAX_PUBLIC_NAME_LENGTH) return normalized
  const hash = createHash('sha256').update(serverName + '\0' + rawName).digest('hex').slice(0, HASH_LENGTH)
  return normalized.slice(0, MAX_PUBLIC_NAME_LENGTH - HASH_LENGTH - 1) + '_' + hash
}

function text(value: string): ContentBlock[] {
  return [{ type: 'text', text: value }]
}

function extractText(mcpContent: unknown, toolName: string): string {
  if (!Array.isArray(mcpContent)) return String(mcpContent ?? '')
  const parts: string[] = []
  for (const value of mcpContent) {
    if (typeof value !== 'object' || value === null || Array.isArray(value)) {
      parts.push('[unsupported content type: unknown]')
      continue
    }
    const block = value as Record<string, unknown>
    switch (block.type) {
      case 'text':
        parts.push(block.text === undefined ? '' : String(block.text))
        break
      case 'image':
        parts.push('[image: ' + String(block.mimeType ?? 'unknown') + ', content discarded]')
        break
      case 'audio':
        parts.push('[audio: ' + String(block.mimeType ?? 'unknown') + ', content discarded]')
        break
      case 'resource':
        parts.push('[resource content discarded]')
        break
      case 'resource_link':
        parts.push('[resource_link: ' + String(block.uri ?? '') + ']')
        break
      default:
        parts.push('[unsupported content type: ' + String(block.type ?? 'unknown') + ']')
    }
  }
  if (parts.length === 0) parts.push('[tool ' + toolName + ' returned no text]')
  return parts.join('\n')
}

/** Merge the parent process env with server overrides, dropping undefined values. */
function childEnv(extra: Record<string, string> | undefined): Record<string, string> {
  const env: Record<string, string> = {}
  for (const [key, value] of Object.entries(process.env)) {
    if (value !== undefined) env[key] = value
  }
  Object.assign(env, extra ?? {})
  return env
}

function serverScript(name: string): string {
  const here = dirname(fileURLToPath(import.meta.url))
  const fromSrc = join(here, '..', 'servers', name)
  const fromLib = join(here, '..', '..', 'servers', name)
  if (existsSync(fromSrc)) return fromSrc
  if (existsSync(fromLib)) return fromLib
  return fromSrc
}

/** Resolve config.servers to concrete transport descriptors. */
export function resolveServers(config: RezConfig): ServerDescriptor[] {
  const descriptors: ServerDescriptor[] = []
  for (const [id, server] of Object.entries(config.servers)) {
    if (!server.enabled) continue
    const descriptor: ServerDescriptor = {
      id,
      serverName: id,
      transport: server.transport,
      command: server.command,
      args: server.args,
      env: server.env,
      cwd: server.cwd,
      url: server.url,
      headers: server.headers,
      toolCallTimeoutMs: server.toolCallTimeoutMs ?? 60000,
    }

    // Bundled local servers: launch our own scripts unless the user overrode args.
    if (id === 'fs' || id === 'sqlite') {
      descriptor.command = descriptor.command ?? process.execPath
      const script = id === 'fs' ? 'fs-mcp-server.mjs' : 'sqlite-mcp-server.mjs'
      descriptor.args = descriptor.args !== undefined && descriptor.args.length > 0 ? descriptor.args : [serverScript(script)]
    }

    descriptors.push(descriptor)
  }
  return descriptors
}

export class McpHost {
  private connections = new Map<RezServerId, LiveConnection>()
  private enabledIds = new Set<RezServerId>()
  private role: RezRoleId = 'all'
  private billing: RezConfig['billing'] = { inputCostPer1k: 0.001, outputCostPer1k: 0.002, monthlyBudget: 0 }
  private syncChain: Promise<void> = Promise.resolve()
  private readonly ctx: Context
  private readonly tokenManager: TokenManager

  constructor(ctx: Context, tokenManager: TokenManager) {
    this.ctx = ctx
    this.tokenManager = tokenManager
  }

  /** Serialize reconciliation so concurrent settings callbacks cannot double-register tools. */
  sync(config: RezConfig): Promise<void> {
    this.syncChain = this.syncChain.then(() => this.syncInner(config)).catch(error => {
      console.warn('[dsh-rez-suite] MCP sync failed:', error)
    })
    return this.syncChain
  }

  /** Reconcile live connections with the current configuration. */
  private async syncInner(config: RezConfig): Promise<void> {
    const roleChanged = this.role !== config.role
    this.role = config.role
    this.billing = config.billing
    const wanted = resolveServers(config)
    const wantedIds = new Set(wanted.map(descriptor => descriptor.id))
    this.enabledIds = new Set(wantedIds)

    for (const [id] of [...this.connections]) {
      if (!wantedIds.has(id)) {
        await this.disposeConnection(id)
      }
    }

    for (const descriptor of wanted) {
      const existing = this.connections.get(descriptor.id)
      const signature = JSON.stringify([descriptor.transport, descriptor.command, descriptor.args, descriptor.env, descriptor.cwd, descriptor.url, descriptor.headers])
      if (existing !== undefined) {
        const oldSignature = JSON.stringify([existing.descriptor.transport, existing.descriptor.command, existing.descriptor.args, existing.descriptor.env, existing.descriptor.cwd, existing.descriptor.url, existing.descriptor.headers])
        if (!roleChanged && oldSignature === signature) continue
        await this.disposeConnection(descriptor.id)
      }
      try {
        await this.startConnection(descriptor)
      } catch (error) {
        console.warn('[dsh-rez-suite] MCP ' + descriptor.id + ' start failed:', error)
      }
    }
  }

  private async startConnection(descriptor: ServerDescriptor): Promise<void> {
    const connection = await this.connect(descriptor)
    const definitions: Array<{ definition: ToolDefinition; publicName: string }> = []
    for (const tool of connection.tools) {
      if (!isToolAllowed(this.role, descriptor.serverName, tool.rawName)) continue
      const publicName = publicToolName(descriptor.serverName, tool.rawName)
      definitions.push({ definition: this.buildDefinition(descriptor, connection, tool, publicName), publicName })
    }

    const disposers = new Map<string, () => void>()
    try {
      for (const { definition, publicName } of definitions) {
        disposers.set(publicName, this.ctx.tools.register(definition))
      }
    } catch (error) {
      for (const dispose of disposers.values()) dispose()
      await this.closeConnection(connection)
      throw error
    }
    connection.disposers = disposers
    this.connections.set(descriptor.id, connection)
    console.info('[dsh-rez-suite] MCP ' + descriptor.id + ' connected, registered ' + disposers.size + ' tools (role=' + this.role + ')')
  }

  private buildDefinition(descriptor: ServerDescriptor, connection: LiveConnection, tool: McpToolInfo, publicName: string): ToolDefinition {
    const rawName = tool.rawName
    const serverId = descriptor.id
    const execute = async (args: unknown, exec: { signal: AbortSignal }): Promise<unknown> => {
      const started = Date.now()
      const callArgs = typeof args === 'object' && args !== null ? (args as Record<string, unknown>) : {}
      try {
        const result = await (connection.client as unknown as {
          request(method: unknown, schema: unknown, options?: { signal?: AbortSignal; timeout?: number }): Promise<Record<string, unknown>>
        }).request(
          { method: 'tools/call', params: { name: rawName, arguments: callArgs } },
          RawCallToolResultSchema,
          { signal: exec.signal, timeout: descriptor.toolCallTimeoutMs },
        )
        const content = Array.isArray(result.content) ? result.content : []
        const rendered = extractText(content, rawName)
        if (result.isError === true) {
          throw new Error(rendered)
        }
        this.recordUsage(serverId, rawName, true, callArgs, rendered, Date.now() - started)
        return {
          content,
          ...(result.structuredContent !== undefined ? { structuredContent: result.structuredContent } : {}),
        }
      } catch (error) {
        this.recordUsage(serverId, rawName, false, callArgs, error instanceof Error ? error.message : String(error), Date.now() - started)
        throw error
      }
    }

    return {
      name: publicName,
      description: tool.description,
      parameters: tool.inputSchema,
      output: {
        schema: {
          type: 'object',
          properties: {
            content: { type: 'array', items: {} },
            structuredContent: {},
          },
          required: ['content'],
          additionalProperties: false,
        },
        render: (_args: unknown, value: unknown): ContentBlock[] => {
          const record = (value ?? {}) as Record<string, unknown>
          return text(extractText(record.content, rawName))
        },
      },
      execute,
    } as unknown as ToolDefinition
  }

  private recordUsage(server: RezServerId, tool: string, ok: boolean, args: unknown, output: string, durationMs: number): void {
    const inputTokens = estimateTokens(args)
    const outputTokens = estimateTokens(output)
    const cost = (inputTokens / 1000) * this.billing.inputCostPer1k + (outputTokens / 1000) * this.billing.outputCostPer1k
    this.tokenManager.record({
      server,
      tool,
      role: this.role,
      inputTokens,
      outputTokens,
      cost,
      durationMs,
      ok,
      error: ok ? undefined : output,
    })
  }

  private async connect(descriptor: ServerDescriptor): Promise<LiveConnection> {
    const client = new Client({ name: 'dsh-rez-suite', version: '0.1.0' })
    const transport = descriptor.transport === 'stdio'
      ? new StdioClientTransport({
          command: descriptor.command ?? '',
          args: descriptor.args ?? [],
          env: childEnv(descriptor.env),
          cwd: descriptor.cwd,
          stderr: 'pipe',
        })
      : new StreamableHTTPClientTransport(new URL(descriptor.url ?? ''), {
          requestInit: { headers: descriptor.headers ?? {} },
        })
    await client.connect(transport)
    const tools = await listTools(client)
    return {
      descriptor,
      client,
      transport,
      tools,
      disposers: new Map(),
      startedAt: Date.now(),
    }
  }

  private async closeConnection(connection: LiveConnection): Promise<void> {
    for (const dispose of connection.disposers.values()) {
      try { dispose() } catch { /* ignore */ }
    }
    try { await connection.transport.close() } catch { /* ignore */ }
    try { await connection.client.close() } catch { /* ignore */ }
  }

  private async disposeConnection(id: RezServerId): Promise<void> {
    const connection = this.connections.get(id)
    if (connection === undefined) return
    this.connections.delete(id)
    await this.closeConnection(connection)
  }

  /** Test every enabled server with a throwaway connection. */
  async test(config: RezConfig): Promise<RezTestResult[]> {
    const results: RezTestResult[] = []
    for (const descriptor of resolveServers(config)) {
      const started = Date.now()
      let connection: LiveConnection | undefined
      try {
        connection = await this.connect(descriptor)
        const serverInfo = (connection.client.getServerVersion?.() as { name?: string; version?: string } | undefined)
        results.push({
          server: descriptor.id,
          ok: true,
          toolCount: connection.tools.length,
          serverInfo: serverInfo ? serverInfo.name + ' ' + serverInfo.version : undefined,
          latencyMs: Date.now() - started,
        })
      } catch (error) {
        results.push({
          server: descriptor.id,
          ok: false,
          latencyMs: Date.now() - started,
          error: error instanceof Error ? error.message : String(error),
        })
      } finally {
        if (connection !== undefined) await this.closeConnection(connection)
      }
    }
    return results
  }

  status(_room?: string): RezServerStatus[] {
    const ids = new Set<string>([...this.enabledIds, ...this.connections.keys()])
    return [...ids].sort().map(id => {
      const connection = this.connections.get(id)
      if (connection === undefined) {
        return { server: id, enabled: this.enabledIds.has(id), state: 'disconnected', toolCount: 0, registeredTools: 0 }
      }
      return {
        server: id,
        enabled: true,
        state: 'connected',
        toolCount: connection.tools.length,
        registeredTools: connection.disposers.size,
        lastError: connection.lastError,
        startedAt: connection.startedAt,
      }
    })
  }

  async dispose(): Promise<void> {
    for (const id of [...this.connections.keys()]) {
      await this.disposeConnection(id)
    }
  }
}

/** Drain uncached tools/list pagination (mirrors dsh-mcp-client). */
async function listTools(client: Client): Promise<McpToolInfo[]> {
  const tools: McpToolInfo[] = []
  let cursor: string | undefined
  do {
    const response = await (client as unknown as {
      request(method: unknown, schema: unknown): Promise<{ tools: Array<Record<string, unknown>>; nextCursor?: string }>
    }).request(
      { method: 'tools/list', ...(cursor === undefined ? {} : { params: { cursor } }) },
      ListToolsResultSchema,
    )
    for (const raw of response.tools) {
      tools.push({
        rawName: String(raw.name),
        description: raw.description === undefined ? '' : String(raw.description),
        inputSchema: typeof raw.inputSchema === 'object' && raw.inputSchema !== null ? raw.inputSchema as Record<string, unknown> : { type: 'object' },
      })
    }
    cursor = response.nextCursor
  } while (cursor !== undefined)
  return tools
}
