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'

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

	const agents = createAgents(new MessageDispatcher(ws), fsStatePersistence, fsContextPersistence)

	await agents.load()

	// Queue websocket message handling so client-side multi-send sequences (e.g. select state -> send chat)
	// are applied deterministically and don't race when handlers `await`.
	let messageQueue = Promise.resolve()

	ws.on('message', (event) => {
		const raw = event.toString()

		messageQueue = messageQueue
			.then(async () => {
				let msg: WsMessage
				try {
					msg = JSON.parse(raw) as WsMessage
				} catch (error) {
					console.error('Error parsing websocket message', error)
					return
				}

				// @ts-ignore
				console.log('--> ', msg.channel, msg.event?.type || '')

				switch (msg.channel) {
					case 'app-events':
						switch (msg.event.type) {
							case 'select-agent':
								await agents.select(msg.event.agent, msg.event.state, msg.event.region)
								break
							case 'reload-project':
								await agents.reload()
								break
							case 'context-updated':
								await agents.updateContext(msg.event.context)
								break
							case 'prompt-updated':
								await agents.updatePrompt(msg.event.prompt)
								break
							case 'trigger-action':
								await agents.triggerAction(msg.event.action)
								break
							case 'step-selected':
								await agents.selectStep(msg.event.step)
								break
							case 'hangup':
								await agents.hangup(msg.event.agentId, msg.event.region)
								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)
				try {
					ws.send(JSON.stringify({ channel: 'error', message: String(error) }))
				} catch {}
			})
	})

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