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

const stateDir =
  process.env.GEELIB_STATE_DIR ||
  join(homedir(), '.claude', 'channels', 'geelib')
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] geelib-channel boot.mjs start pid=${process.pid}`)
log(
  `[BOOT] env GEELIB_STATE_DIR=${process.env.GEELIB_STATE_DIR || ''} GEELIB_POLL_INTERVAL_MS=${process.env.GEELIB_POLL_INTERVAL_MS || ''} GEELIB_SUB_ID=${process.env.GEELIB_SUB_ID || ''}`,
)

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')
