#!/usr/bin/env node

const { promises } = require('fs')
const path = require('path')
const childProcess = require('child_process')
const docgen = require('react-docgen-typescript')

const main = async () => {
  const configFilePath = path.resolve(process.cwd(), 'docs.config.json')
  const docsConfigBuffer = await promises.readFile(configFilePath)
  const docsConfigString = docsConfigBuffer.toString('utf-8')
  const docsConfig = JSON.parse(docsConfigString)

  try {
    //await promises.mkdir('.docs')
    //await childProcess.exec('npx create-next-app dummy-docs --ts')
    //await promises.rmdir('.docs')
    //await promises.rename('dummy-docs', '.docs')
  } catch {

  }

  const getSources = (nav) => nav.reduce(
    (sourcesToParse, navItem) => {
      if (navItem?.source?.endsWith('.tsx')) {
        return [
          ...sourcesToParse,
          navItem,
          ...(Array.isArray(navItem?.children) ? getSources(navItem.children) : []),
        ]
      }

      return [
        ...sourcesToParse,
        ...(Array.isArray(navItem?.children) ? getSources(navItem.children) : []),
      ]
    },
    []
  )

  const sources = getSources(docsConfig.nav)
  const docgenInfo = docgen.parse(
    sources.map(s => path.resolve(process.cwd(), s.source)),
    {
      shouldExtractLiteralValuesFromEnum: true,
      shouldRemoveUndefinedFromOptional: true,
      propFilter: (prop) => {
        if (prop.declarations !== undefined && prop.declarations.length > 0) {
          const hasPropAdditionalDescription = prop.declarations.find((declaration) => {
            return !declaration.fileName.includes("node_modules");
          });

          return Boolean(hasPropAdditionalDescription);
        }

        return true;
      },
    }
  )
  const sourcesWithDocgenInfo = sources.map((s, i) => ({
    ...s,
    docgen: docgenInfo[i],
  }))

  console.log(JSON.stringify(sourcesWithDocgenInfo, null, 2))
}

void main()
