import { APPS_DIR, allApps, onChange, renameApp, startApp, stopApp, updateAppIcon } from '$apps'
import type { App as BackendApp } from '$apps'
import type { App as SharedApp } from '@types'
import { generateTemplates, type TemplateType } from '%templates'
import { Hype } from '@because/hype'
import { existsSync, mkdirSync, symlinkSync, writeFileSync } from 'fs'
import { dirname, join } from 'path'

const timestamp = () => {
  const d = new Date()
  const pad = (n: number) => String(n).padStart(2, '0')
  return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
}

const router = Hype.router()

// BackendApp -> SharedApp
function convert(app: BackendApp): SharedApp {
  const clone = { ...app }
  delete clone.proc
  delete clone.logs
  return clone
}

// SSE endpoint for real-time app state updates
router.sse('/stream', (send) => {
  const broadcast = () => {
    const apps: SharedApp[] = allApps().map(({
      name, state, icon, error, port, started, logs, tool
    }) => ({
      name, state, icon, error, port, started, logs, tool,
    }))
    send(apps)
  }

  broadcast()
  const unsub = onChange(broadcast)
  return () => unsub()
})

router.get('/', c => c.json(allApps().map(convert)))

router.get('/:app', c => {
  const appName = c.req.param('app')
  if (!appName) return c.json({ error: 'App not found' }, 404)

  const app = allApps().find(a => a.name === appName)
  if (!app) return c.json({ error: 'App not found' }, 404)

  return c.json(convert(app))
})

router.get('/:app/logs', c => {
  const appName = c.req.param('app')
  if (!appName) return c.json({ error: 'App not found' }, 404)

  const app = allApps().find(a => a.name === appName)
  if (!app) return c.json({ error: 'App not found' }, 404)

  return c.json(app.logs ?? [])
})

router.post('/', async c => {
  let body: { name?: string, template?: TemplateType, tool?: boolean }
  try {
    body = await c.req.json()
  } catch {
    return c.json({ ok: false, error: 'Invalid JSON body' }, 400)
  }

  const name = body.name?.trim().toLowerCase().replace(/\s+/g, '-')
  if (!name) return c.json({ ok: false, error: 'App name is required' }, 400)

  if (!/^[a-z][a-z0-9-]*$/.test(name)) {
    return c.json({ ok: false, error: 'Name must start with a letter and contain only lowercase letters, numbers, and hyphens' }, 400)
  }

  const appPath = join(APPS_DIR, name)
  if (existsSync(appPath)) {
    return c.json({ ok: false, error: 'An app with this name already exists' }, 400)
  }

  const template = body.template ?? 'ssr'
  const templates = generateTemplates(name, template, { tool: body.tool })

  // Create versioned directory structure
  const ts = timestamp()
  const versionPath = join(appPath, ts)
  const currentPath = join(appPath, 'current')

  // Create directories and write files into version directory
  for (const [filename, content] of Object.entries(templates)) {
    const fullPath = join(versionPath, filename)
    const dir = dirname(fullPath)
    if (!existsSync(dir)) {
      mkdirSync(dir, { recursive: true })
    }
    writeFileSync(fullPath, content)
  }

  // Create current symlink
  symlinkSync(ts, currentPath)

  return c.json({ ok: true, name })
})

router.sse('/:app/logs/stream', (send, c) => {
  const appName = c.req.param('app')
  const targetApp = allApps().find(a => a.name === appName)
  if (!targetApp) return

  let lastLogCount = 0

  const sendNewLogs = () => {
    const currentApp = allApps().find(a => a.name === appName)
    if (!currentApp) return

    const logs = currentApp.logs ?? []
    const newLogs = logs.slice(lastLogCount)
    lastLogCount = logs.length

    for (const line of newLogs) {
      send(line)
    }
  }

  sendNewLogs()
  const unsub = onChange(sendNewLogs)
  return () => unsub()
})

router.post('/:app/start', c => {
  const appName = c.req.param('app')
  if (!appName) return c.json({ error: 'App not found' }, 404)

  startApp(appName)
  return c.json({ ok: true })
})

router.post('/:app/restart', c => {
  const appName = c.req.param('app')
  if (!appName) return c.json({ error: 'App not found' }, 404)

  stopApp(appName)
  startApp(appName)
  return c.json({ ok: true })
})

router.post('/:app/stop', c => {
  const appName = c.req.param('app')
  if (!appName) return c.json({ error: 'App not found' }, 404)

  stopApp(appName)
  return c.json({ ok: true })
})

router.post('/:app/icon', c => {
  const appName = c.req.param('app')
  const icon = c.req.query('icon') ?? ''
  if (!icon) return c.json({ error: 'No icon query param provided' })

  try {
    updateAppIcon(appName, icon)
    return c.json({ ok: true })
  } catch (error) {
    return c.json({ error })
  }
})

router.post('/:app/rename', async c => {
  const appName = c.req.param('app')

  let body: { name?: string }
  try {
    body = await c.req.json()
  } catch {
    return c.json({ ok: false, error: 'Invalid JSON body' }, 400)
  }

  const newName = body.name?.trim().toLowerCase().replace(/\s+/g, '-')

  if (!newName) return c.json({ ok: false, error: 'New name is required' }, 400)

  const result = renameApp(appName, newName)
  if (!result.ok) return c.json(result, 400)

  return c.json({ ok: true, name: newName })
})

export default router
