import { toString as qrToString } from 'qrcode'
import { generateToken } from '../../rc/auth.js'
import { startRCServer, isRCServerRunning } from '../../rc/server.js'
import { getTailscaleIP } from '../../rc/tailscale.js'

const DEFAULT_PORT = 7390

export async function rcServeHandler(opts: { port?: number }): Promise<void> {
  if (isRCServerRunning()) {
    console.error('RC server is already running.')
    process.exit(1)
  }

  const port = opts.port ?? DEFAULT_PORT
  const token = generateToken()

  try {
    await startRCServer({ port, host: '0.0.0.0', token })

    const tsIP = await getTailscaleIP()
    const host = tsIP ?? 'localhost'
    const connectUrl = `http://${host}:${port}?token=${token}`

    const qr = await qrToString(connectUrl, {
      type: 'utf8',
      errorCorrectionLevel: 'L',
    }).catch(() => null)

    console.log('')
    console.log('━━━ SANDCODE Remote Control Server ━━━')
    console.log('')
    if (qr) console.log(qr)
    console.log(`Scan QR or open: ${host}:${port}`)
    console.log('')
    console.log('Waiting for sessions and clients...')
    console.log('Press Ctrl+C to stop.')
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━')
    console.log('')

    // Keep alive until signal
    await new Promise<void>((resolve) => {
      process.on('SIGINT', resolve)
      process.on('SIGTERM', resolve)
    })

    console.log('\nStopping RC server...')
    process.exit(0)
  } catch (err) {
    console.error('Failed to start RC server:', err instanceof Error ? err.message : String(err))
    process.exit(1)
  }
}
