import { allApps, initApps } from '$apps'
import appsRouter from './api/apps'
import syncRouter from './api/sync'
import { Hype } from '@because/hype'

const app = new Hype({ layout: false })

app.route('/api/apps', appsRouter)
app.route('/api/sync', syncRouter)

// Tool URLs: /tool/code?app=todo&file=README.md -> redirect to tool port
app.get('/tool/:tool', c => {
  const toolName = c.req.param('tool')
  const tool = allApps().find(a => a.tool && a.name === toolName)
  if (!tool || tool.state !== 'running' || !tool.port) {
    return c.text(`Tool "${toolName}" not found or not running`, 404)
  }
  const params = new URLSearchParams(c.req.query()).toString()
  const url = params ? `http://localhost:${tool.port}?${params}` : `http://localhost:${tool.port}`
  return c.redirect(url)
})

console.log('🐾 Toes!')
initApps()

export default {
  ...app.defaults,
  maxRequestBodySize: 1024 * 1024 * 50, // 50MB
}
