text: 'use strict'
  
  const cheerio = require('cheerio')
  const axios = require('axios')
  const path = require('path')
  const fs = require('fs')
  
  const directory = 'static'
  const websiteUrl = 'https://dreifragezeichen.de'
  const archiveUrl = `${websiteUrl}/produktwelt/hoerspiele`
  
  const requestPage = async (url) => {
    try {
      const response = await axios.get(url)
      return response.data
    } catch (error) {
      console.error('An error occurred while requesting a page: ', url)
      handleHTTPError(error)
      process.exit(1)
    }
  }
  
  const downloadImage = async (url, imagePath) => {
    const writer = fs.createWriteStream(path.resolve(__dirname, imagePath))
  
    let response
    try {
      response = await axios({
        url: 'https:' + url,
        method: 'GET',
        responseType: 'stream',
      })
    } catch (error) {
      console.error('An error occurred while downloading an image: ', url)
      handleHTTPError(error)
      process.exit(1)
    }
  
    await response.data.pipe(writer)
  
    return new Promise((resolve, reject) => {
      writer.on('finish', resolve)
      writer.on('error', reject)
    })
  }
  
  const handleHTTPError = (error) => {
    if (error.response) {
      console.error('data', error.response.data)
      console.error('status', error.response.status)
      console.error('headers', error.response.headers)
    } else if (error.request) {
      console.error('request', error.request)
    } else {
      console.error('message', error.message)
    }
  }
  
  const collectEpisodeLinks = ($currentPage) =>
    $currentPage('.product-info')
      .find('a')
      .toArray()
      .map((el) => {
        const serviceMap = {
          spotify: ['spotify'],
          appleMusic: ['apple', 'app=music'],
          appleITunes: ['apple', 'app=itunes'],
          youTubeMusic: ['music.youtube'],
        }
  
        const link = $currentPage(el).attr('href')
        const service = Object.keys(serviceMap).find((key) =>
          serviceMap[key].every((keyword) => link.includes(keyword))
        )
  
        return {
          link,
          service,
        }
      })
      .filter((link) => link.service === 'spotify') // Limiting the links to spotify for now
  
  ;(async function main() {
    console.info('Start processing episodes.\n')
  
    const firstPage = await requestPage(archiveUrl)
    const $firstPage = cheerio.load(firstPage)
    const pageCount = $firstPage('ul.pagination')
      .children()
      .last()
      .find('a')
      .attr('href')
      .split('page=')[1]
  
    const episodeUrls = []
    for (let i = 1; i <= pageCount; i++) {
      console.info(`Collecting episode website urls from archive page ${i}.`)
      const currentPage = await requestPage(`${archiveUrl}?page=${i}`)
      const $currentPage = cheerio.load(currentPage)
      $currentPage('.card-expander-content').each(function () {
        episodeUrls.push($currentPage(this).find('a.btn-primary').attr('href'))
      })
    }
  
    const episodes = []
    for (let index = 0; index < episodeUrls.length; index++) {
      const episode = {
        type: '',
        name: '',
        links: [],
        title: '',
        cover: '',
        number: null,
        homepage: '',
        releaseDate: '',
      }
  
      episode.homepage = `${websiteUrl}${episodeUrls[index]}`
  
      console.info(`Processing ${episode.homepage}.`)
      const currentPage = await requestPage(episode.homepage)
      const $currentPage = cheerio.load(currentPage)
  
      episode.title = $currentPage('.product-info .title')
        .find(':header')
        .toArray()
        .map((el) => $currentPage(el).text())
        .join(', ')
  
      if (episode.title.includes('Steelbook')) {
        console.info(`Skipping due to identifying as a steelbook collection.\n`)
        continue
      }
  
      if (episode.title.includes('Folge')) {
        episode.type = 'episode'
        episode.name = episode.title.split(',')[2].trim()
        episode.number = episode.title.split(',')[1].replace('Folge', '').trim()
        episode.cover = `${episode.number}-${episode.title
          .split(',')[2]
          .trim()
          .split(' ')
          .join('-')
          .toLowerCase()}.jpg`
      } else {
        episode.type = 'special'
        episode.name = episode.title.replace('Die drei ???', '').trim()
        episode.number = 0
        episode.cover = `${episode.number}-${episode.name
          .split(' ')
          .join('-')
          .toLowerCase()}.jpg`
      }
  
      episode.links = collectEpisodeLinks($currentPage)
  
      if (!episode.links.length) {
        console.info(`Skipping due to missing links.\n`)
        continue
      }
  
      downloadImage(
        $currentPage('.product-cover').attr('src'),
        `${directory}/covers/${episode.cover}`
      )
  
      episode.releaseDate = $currentPage('.product-info')
        .find('span:contains("Veröffentlichungsdatum")')
        .text()
        .replace('Veröffentlichungsdatum:', '')
        .trim()
  
      episode.description = $currentPage('#info-inhalt').find('p').text().trim()
  
      console.info(
        `Episode ${episode.number}: ${episode.name} processed successfully.\n`
      )
      episodes.push(episode)
    }
  
    fs.writeFileSync(
      path.resolve(__dirname, `${directory}/episodes.json`),
      JSON.stringify(episodes, null, 4)
    )
  
    console.info('All episodes processed successfully.')
  })()
  