import { z } from 'zod';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { config } from '../../config.js';
import { errorResult, jsonResult, toErrorMessage } from '../shared.js';
import { dockerManager } from './dockerManager.js';

export function registerDockerContainerLogsTool(server: McpServer): void {
  server.registerTool(
    'docker_get_container_logs',
    {
      title: 'Docker Get Container Logs',
      description:
        'Fetch logs from a running or stopped Docker container started by this server.',
      inputSchema: {
        containerId: z.string().min(1).describe('Container ID (short or long) returned by docker_run_container.'),
        tail: z
          .number()
          .int()
          .positive()
          .optional()
          .default(200)
          .describe('Only return the last N lines.'),
        follow: z
          .boolean()
          .optional()
          .default(false)
          .describe('Stream logs (not implemented; kept for API compatibility).'),
      },
    },
    async ({ containerId, tail, follow }) => {
      try {
        await dockerManager.ensureReachable();
        if (follow) {
          return jsonResult({
            containerId,
            note: 'Live log streaming is not supported via this tool; use docker_get_container_logs with follow:false to poll.',
            logs: '',
          });
        }

        const docker = dockerManager.getDocker();
        const buffer = await docker.getContainer(containerId).logs({
          stdout: true,
          stderr: true,
          tail,
        });
        const raw = Buffer.isBuffer(buffer) ? buffer.toString('utf8') : String(buffer);
        return jsonResult({
          containerId,
          logs: raw.slice(-config.maxToolOutputChars),
          bytes: raw.length,
        });
      } catch (error) {
        return errorResult(toErrorMessage(error));
      }
    },
  );
}
