import { mkdirSync, appendFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { homedir } from 'node:os'

const stateDir =
  process.env.WS_STATE_DIR ||
  join(homedir(), '.claude', 'channels', 'ws')
const bootLog = join(stateDir, 'boot.log')
mkdirSync(dirname(bootLog), { recursive: true })

function log(line) {
  appendFileSync(bootLog, `${new Date().toISOString()} ${line}\n`, {
    encoding: 'utf8',
    mode: 0o600,
    flag: 'a',
  })
}

log(`[BOOT] ws-channel boot.mjs start pid=${process.pid}`)
log(`[BOOT] WS_PORT=${process.env.WS_PORT || ''} WS_MAIN_RPC_SOCKET=${process.env.WS_MAIN_RPC_SOCKET || ''}`)

process.on('uncaughtException', err => {
  log(`[BOOT] uncaughtException ${err?.stack || err}`)
})
process.on('unhandledRejection', err => {
  log(`[BOOT] unhandledRejection ${err?.stack || err}`)
})

await import('./index.mjs')
log('[BOOT] imported index.mjs successfully')
