import { readLines } from 'https://deno.land/std/io/buffer.ts'
import { copy } from 'https://deno.land/std/streams/conversion.ts'
const print = console.log

type type = [search: RegExp, replace: string]

// Pass-through the header
print(`20 ${ Deno.args.join(';') }\r`)

// Check for type=inline parameter
const inline = Deno.args.find(
  (arg) =>
    arg.trim().startsWith('type=') &&
    arg.split('=')[1].split(',').includes('inline')
)

// Pass-through the body if no type=inline
if (!inline) {
  await copy(Deno.stdin, Deno.stdout)
  Deno.exit()
}

const types: type[] = [
  [/_([^_]+)_/g,       '\x1b[3m$1\x1b[0m'],  // italic
  [/\*\*([^*]+)\*\*/g, '\x1b[1m$1\x1b[0m'],  // bold
]

const replace = (text: string, type: type): string =>
  text.replaceAll(...type)

const format = (text: string): string =>
  types.reduce(replace, text)

let preformatting = false

for await (const line of readLines(Deno.stdin)) {
  // Toggle preformatting lines
  if (line.startsWith('```')) {
    preformatting = !preformatting
    print(line)
  }
  // Skip preformatted, header and link lines
  else if (preformatting || line.startsWith('#') || line.startsWith('=>')) {
    print(line)
  }
  // Format list item lines
  else if (line.startsWith('* ')) {
    print(`* ${ format(line.slice(2)) }`)
  }
  // Format text and quote lines
  else {
    print(format(line))
  }
}