#!/usr/bin/env node
import { parseArgs } from 'node:util'
import { resolve } from 'node:path'
import { composeItem } from '../src/item.js'
import { composeSchedule } from '../src/schedule-compose.js'
import { previewItem, previewSchedule } from '../src/preview.js'
import { resolveSlug } from '../src/resolve.js'
import { loadDeckMeta } from '../src/config.js'

const HELP = `\
usage: marp-compose [-C <dir>] <slug> [options]

  marp-compose <slug>            compose a topic or schedule deck

options:
  -C <dir>           change working directory
  --preview, -p      compose and open in live-preview mode
  --draft            skip missing content slugs (insert placeholder slide)
  --help, -h         show this help
`

const { values, positionals } = parseArgs({
  args: process.argv.slice(2),
  options: {
    C:       { type: 'string',  short: 'C' },
    preview: { type: 'boolean', short: 'p' },
    draft:   { type: 'boolean' },
    help:    { type: 'boolean', short: 'h' },
  },
  allowPositionals: true,
})

if (values.help) { process.stdout.write(HELP); process.exit(0) }
if (values.C) process.chdir(resolve(values.C))

const slug = positionals[0]
if (!slug) { console.error('usage: marp-compose [-C <dir>] <slug>'); process.exit(1) }

let resolved
try {
  resolved = resolveSlug(slug, { root: process.cwd() })
} catch (err) {
  console.error(`error: ${err.message}`)
  process.exit(1)
}

if (values.preview) {
  if (resolved.type === 'schedule') {
    await previewSchedule(slug, { draft: values.draft })
  } else {
    await previewItem(slug)
  }
  // server keeps process alive
} else {
  const deckMeta = resolved.type === 'schedule' ? await loadDeckMeta(process.cwd()) : {}

  async function main() {
    if (resolved.type === 'schedule') {
      try {
        const { status } = await composeSchedule(slug, [], { draft: values.draft, deckMeta })
        process.exit(status)
      } catch (err) {
        if (err.message?.includes('not found') || err.message?.includes('timings')) {
          console.error(`error: ${err.message}`)
          process.exit(1)
        }
        throw err
      }
    }

    process.exit(await composeItem(slug, []))
  }

  main()
}
