import { MCPServer, getWebKitClient } from '../mcp-server';
import { getNetworkInterceptorForSession } from './network-intercept';
import { ErrorCode, respondWithStructuredError } from '../errors';

export function registerNetworkOfflineTool(server: MCPServer): void {
  server.registerTool(
    {
      name: 'network_offline',
      description: 'Simulate offline mode by blocking all network requests.',
      inputSchema: {
        type: 'object' as const,
        properties: {
          enabled: { type: 'boolean', description: 'true to go offline, false to restore connectivity' },
          device_id: { type: 'string', description: 'Simulator UDID / WebKit connection to target (uses active device if omitted)' },
        },
        required: ['enabled'],
      },
    },
    async (sessionId: string, params: Record<string, unknown>) => {
      const deviceId = typeof params.device_id === 'string' ? params.device_id : undefined;
      const client = getWebKitClient(deviceId);
      if (!client)
        return respondWithStructuredError(ErrorCode.BACKEND_NOT_CONNECTED, 'Safari not connected');
      const enabled = params.enabled as boolean;
      // Pass deviceId so the offline toggle targets the per-device interceptor
      // and does not bleed state across simulators in multi-device sessions
      // (Codex review on PR #762).
      await getNetworkInterceptorForSession(sessionId, deviceId).setOffline(enabled, client);
      return { content: [{ type: 'text' as const, text: enabled ? 'Offline mode enabled' : 'Online mode restored' }] };
    },
  );
}
