import { WebSocket } from 'ws'
import type { WsMessage } from '../lib/ws-message'
import { createAgents } from './agents'
import { fsContextPersistence, fsStatePersistence } from './fs-persistence'
import { MessageDispatcher } from './message-dispatcher'
import type { StepTracer } from '@recombine-ai/engine'

export async function oldServer(ws: WebSocket) {
	console.log('== Client connected ==')

	const stepTracer: StepTracer = {
		addStepTrace: (stepTrace) => {
			// TODO: client doesn't react to step traces yet - but should
			ws.send(
				JSON.stringify({
					channel: 'app-events',
					event: { type: 'step-trace', stepTrace }
				})
			)
		}
	}
	const agents = createAgents(
		new MessageDispatcher(ws),
		stepTracer,
		fsStatePersistence,
		fsContextPersistence
	)

	agents.load()

	ws.on('message', async (event) => {
		const msg = JSON.parse(event.toString()) as WsMessage
		// @ts-ignore
		console.log('--> ', msg.channel, msg.event?.type || '')
		try {
			switch (msg.channel) {
				case 'app-events':
					switch (msg.event.type) {
						case 'select-agent':
							await agents.select(msg.event.agent, msg.event.state)
							break
						case 'context-updated':
							agents.updateContext(msg.event.context)
							break
						case 'prompt-updated':
							agents.updatePrompt(msg.event.prompt)
							break
						case 'trigger-action':
							agents.triggerAction(msg.event.action)
							break
						case 'step-selected':
							agents.selectStep(msg.event.step)
							break

						default:
							console.error(`Unknown event type: ${msg.event.type}`)
					}
					break
				case 'chat':
					await agents.handleMessage(msg.message)
					break
				default:
					console.error(`Unknown channel: ${msg.channel}`)
			}
		} catch (error) {
			console.error('Error handling message', error)
			ws.send(JSON.stringify({ channel: 'error', message: String(error) }))
		}
	})

	ws.on('close', async () => {
		// TODO destroy agents here
		console.log('=== client disconnected ===')
	})
}
