import SSSG, { Plugin } from "sssg";
import Variables from "sssg/src/plugins/variables";
import Dev from "sssg/src/plugins/dev";
import TSCompiler from "sssg/src/plugins/ts-compiler";
import MarkdownMetadata, {
  parseMetadata,
} from "sssg/src/plugins/markdown-metadata";
import MarkdownCompiler from "sssg/src/plugins/markdown-compiler";
import CompileTimeJS from "sssg/src/plugins/compile-time-js";
import ImageOptimization from "sssg/src/plugins/image-optimization";

import { $ } from "bun";

import * as path from "path";
import * as fs from "fs";

const sssg = new SSSG({
  outputFolder: path.join(__dirname, "dist"),
  inputFolder: path.join(__dirname, "website"),
});

const gitLogShell =
  await $`git log --pretty=format:'commit=%H%nauthor=%aN <%aE>%ndate=%ad%nmessage=%s%n=========' -1`.quiet();
const gitLogOutput = gitLogShell.text("utf8");
const gitLog = JSON.stringify(parseMetadata(gitLogOutput));
const plugins: Plugin[] = [];

if (process.argv.includes("--dev")) {
  plugins.push(new Dev(sssg));
} else {
  plugins.push(new ImageOptimization());
}

await sssg.run({
  plugins: plugins.concat([
    new CompileTimeJS(),
    new Variables(() => {
      const variables: Record<string, string> = {
        __BLOG_POSTS__: JSON.stringify(
          fs.readdirSync("./website/blogs").map((z) => z.replace(".md", ""))
        ),
        __GIT_LOG_OUTPUT__: gitLog,
      };

      if (fs.existsSync("./website/templates")) {
        for (const file of fs.readdirSync("./website/templates")) {
          const id = file.toUpperCase().replace(".HTML", "");
          variables["__TEMPLATE_" + id + "__"] = fs
            .readFileSync(path.join("./website/templates", file))
            .toString("utf8");
        }
      }
      return variables;
    }),
    new TSCompiler(),
    new MarkdownMetadata(),
    new MarkdownCompiler(),
  ]),
});

await sssg.build();