import { Hono } from 'hono'
import { serveStatic } from 'hono/bun'
import { join, resolve } from 'path'
import { wrapAndRunCode } from './ribbit'

export function startWeb(rootPath: string) {
  const root = resolve(rootPath)
  const app = new Hono()

  // console logging
  app.use("*", async (c, next) => {
    const start = Date.now()
    await next()
    const end = Date.now()
    console.log(`${c.res.status} ${c.req.method} ${c.req.url} (${end - start}ms)`)
  })

  // static files get served out of pub/
  app.use('/*', serveStatic({ root: join(root, 'pub') }))

  app.on(['GET', 'POST'], ['/', '/:page{.+}'], async c => {
    const page = c.req.param('page') || 'index'
    const params = c.req.query()

    const file = Bun.file(join(root, `${page}.sh`))
    if (await file.exists()) {
      return c.html(await wrapAndRunCode(await file.text(), { params }))
    } else {
      return c.text('404 Not Found', 404)
    }
  })

  console.log('🫧 Server started at http://localhost:3000')
  return Bun.serve({
    fetch: app.fetch,
    port: 3000,
  })
}