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

export function registerDockerPushImageTool(server: McpServer): void {
  server.registerTool(
    'docker_push_image',
    {
      title: 'Docker Push Image',
      description:
        'Push a locally built or allow-listed Docker image to a registry (`docker push`). Requires confirm: true. ' +
        'Credentials must already be available via the Docker credential store / environment — never pass secrets as tool args.',
      inputSchema: {
        image: z
          .string()
          .min(1)
          .describe('Image reference to push, e.g. "ghcr.io/org/app:latest" or "my-app:1.0".'),
        confirm: z.boolean().optional().describe('Required as true to push an image.'),
      },
    },
    async ({ image, confirm }) => {
      try {
        if (confirm !== true) {
          return errorResult('docker_push_image requires confirm: true.');
        }
        if (image.includes('--force') || /\s/.test(image)) {
          return errorResult('Invalid image reference.');
        }

        await dockerManager.ensureReachable();

        const result = await runCommand('docker', ['push', image], {
          cwd: config.workspaceRoot,
          timeoutMs: config.scaffoldCommandTimeoutMs,
        });

        return jsonResult({
          image,
          exitCode: result.exitCode,
          failed: result.failed,
          timedOut: result.timedOut,
          output: result.output,
          note: 'Auth must come from `docker login` / credential helpers / env — not from this tool.',
        });
      } catch (error) {
        return errorResult(toErrorMessage(error));
      }
    },
  );
}
