import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { processManager } from '../../lib/processManager.js';
import { dockerManager } from '../docker/dockerManager.js';

function firstString(value: string | string[] | undefined): string {
  if (typeof value === 'string') return value;
  if (Array.isArray(value)) return value[0] ?? '';
  return '';
}

export function registerResources(server: McpServer): void {
  // Process log tail resource (already tracked in processManager).
  server.registerResource(
    'process-logs',
    new ResourceTemplate('workspace://logs/{processId}', { list: undefined }),
    {
      title: 'Process Logs',
      description: 'Live log tail for a background process started by start_dev_server or run_script.',
      mimeType: 'text/plain',
    },
    async (uri, variables) => {
      const processId = firstString(variables.processId);
      try {
        const { info, logs } = processManager.getLogs(processId, 500);
        return {
          contents: [
            {
              uri: uri.href,
              mimeType: 'text/plain',
              text: [
                `Process: ${info.label}`,
                `Command: ${info.command} ${info.args.join(' ')}`,
                `Status: ${info.status}`,
                `PID: ${info.pid ?? 'n/a'}`,
                '---',
                ...logs,
              ].join('\n'),
            },
          ],
        };
      } catch (error) {
        return {
          contents: [
            {
              uri: uri.href,
              mimeType: 'text/plain',
              text: `Error reading process logs: ${error instanceof Error ? error.message : String(error)}`,
            },
          ],
        };
      }
    },
  );

  // Container log tail resource (tracked in dockerManager).
  server.registerResource(
    'container-logs',
    new ResourceTemplate('workspace://containers/{containerId}/logs', { list: undefined }),
    {
      title: 'Container Logs',
      description: 'Log tail for a Docker container started by docker_run_container.',
      mimeType: 'text/plain',
    },
    async (uri, variables) => {
      const containerId = firstString(variables.containerId);
      try {
        await dockerManager.ensureReachable();
        const buffer = await dockerManager.getDocker().getContainer(containerId).logs({
          stdout: true,
          stderr: true,
          tail: 500,
        });
        const raw = Buffer.isBuffer(buffer) ? buffer.toString('utf8') : String(buffer);
        const tracked = dockerManager.getTracked(containerId);
        return {
          contents: [
            {
              uri: uri.href,
              mimeType: 'text/plain',
              text: [
                tracked ? `Container: ${tracked.name} (${tracked.image})` : `Container: ${containerId}`,
                '---',
                raw,
              ].join('\n'),
            },
          ],
        };
      } catch (error) {
        return {
          contents: [
            {
              uri: uri.href,
              mimeType: 'text/plain',
              text: `Error reading container logs: ${error instanceof Error ? error.message : String(error)}`,
            },
          ],
        };
      }
    },
  );
}
