/* eslint-disable no-console */
/* eslint-disable @typescript-eslint/quotes */
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/no-require-imports */
// @ts-check
// 这个文件是用来构建模板中的静态文件的
const fs = require('fs');
const glob = require('glob');
const path = require('path');
const JSON5 = require('json5');
const { spawnSync } = require('child_process');

const PROJECT_ROOT = path.join(__dirname, '..');

const TEMPLATES = [
  {
    sourceDir: path.join(PROJECT_ROOT, 'static-files/rax'),
    outputDir: path.join(PROJECT_ROOT, 'src/plugins/project/framework/rax/template'),
  },
];

try {
  TEMPLATES.forEach(buildTemplateStaticFiles);
  console.log('All done.');
} catch (e) {
  console.error(e);
  process.exit(1);
}

function buildTemplateStaticFiles({ sourceDir, outputDir }) {
  console.log('processing %s template...', path.dirname(sourceDir));

  // 扫描所有的目录
  const sourceFiles = glob.sync('**/*', {
    nodir: true,
    dot: true,
    cwd: sourceDir,
  });

  console.log('got %d files: %o', sourceFiles.length, sourceFiles);

  const staticFiles = {
    imports: [],
    runs: [],
  };

  // 生成对应的文件
  sourceFiles.forEach((sourceFileName, index) => {
    console.log('processing %s', sourceFileName);
    const sourceFileContent = fs.readFileSync(path.join(sourceDir, sourceFileName), 'utf-8');
    const sourceFileRealName = sourceFileName.replace(/\.template$/, '');
    const outputFileName = `${sourceFileRealName}.ts`;
    const outputFileFullPath = path.join(outputDir, 'files', outputFileName);

    const sourceFileExtName = path.extname(sourceFileRealName);
    const sourceFileBaseName = path.basename(sourceFileRealName, sourceFileExtName);

    // 确保目录存在
    fs.mkdirSync(path.dirname(outputFileFullPath), { recursive: true });

    // 写入文件
    fs.writeFileSync(
      outputFileFullPath,
      [
        `/* eslint-disable max-len */`,
        `/* Note: this file is generated by "npm run template", please dont modify this file directly */`,
        `/* -- instead, you should modify "${path.relative(
          PROJECT_ROOT,
          path.join(sourceDir, sourceFileName),
        )}" and run "npm run template" */`,
        `import { ResultFile } from '@alilc/lowcode-types';`,
        '',
        `export default function getFile(): [string[], ResultFile] {`,
        `  return ${JSON5.stringify([
          // 文件目录：
          path.dirname(sourceFileRealName).split(path.sep).filter(Boolean),
          // 文件名和内容:
          {
            name: sourceFileBaseName,
            ext: sourceFileExtName.replace(/^\./, ''),
            content: sourceFileContent,
          },
        ])};`,
        `}`,
        '',
      ].join('\n'),
      {
        encoding: 'utf-8',
      },
    );

    staticFiles.imports.push(`import file${index} from './files/${sourceFileRealName}';`);

    staticFiles.runs.push(`  runFileGenerator(root, file${index})`);
  });

  console.log('generating static-files.ts...');
  fs.writeFileSync(
    path.join(outputDir, 'static-files.ts'),
    [
      `/* Note: this file is generated by "npm run template", please dont modify this file directly */`,
      `import { ResultDir } from '@alilc/lowcode-types';

      import { createResultDir } from '../../../../../utils/resultHelper';
      import { runFileGenerator } from '../../../../../utils/templateHelper';`,
      ...staticFiles.imports,
      '',
      `export function generateStaticFiles(root = createResultDir('.')): ResultDir {`,
      ...staticFiles.runs,
      `  return root;`,
      `}`,
      '',
    ].join('\n'),
    { encoding: 'utf-8' },
  );

  // prettier 一把
  console.log('run prettier...');
  spawnSync('npx', ['prettier', '--write', `${outputDir}`], {
    stdio: 'inherit',
    shell: true,
  });

  console.log('done %s', path.basename(sourceDir));
}
