import { Elysia } from "elysia";
import * as cheerio from "cheerio";
import path from "path";
import fs from "fs/promises";
import { renderTemplate } from "./util";

interface Post {
  title: string;
  path: string;
  date: string;
  date_utc: Date;
}

export const recentPosts = (app: Elysia) =>
  app.get("/recent_posts", async ({ set }) => {
    const postsDir = path.join(process.cwd(), "data/posts");
    const posts: Post[] = [];

    try {
      const entries = await fs.readdir(postsDir, { withFileTypes: true });

      for (const entry of entries) {
        if (entry.isFile() && entry.name.endsWith(".html")) {
          const filePath = path.join(postsDir, entry.name);
          try {
            const fileContent = await fs.readFile(filePath, "utf8");
            const $ = cheerio.load(fileContent);

            // Get a map of the post's metadata tags
            const tags: { [key: string]: string } = {};
            $("meta").each((_i, el) => {
              const name = $(el).attr("name");
              const content = $(el).attr("content");
              if (name && content) {
                tags[name] = content;
              }
            });

            const title = tags["title"] || "Untitled Post";

            const dateStr = tags["date"];
            let date_utc: Date;
            if (dateStr) {
              try {
                date_utc = new Date(dateStr);
                if (isNaN(date_utc.getTime())) {
                  // Check for invalid date
                  date_utc = new Date(0); // Epoch start if invalid
                }
              } catch (e) {
                console.warn(
                  `Could not parse date ${dateStr} for ${entry.name}, using epoch.`,
                  e,
                );
                date_utc = new Date(0); // Epoch start if parsing fails
              }
            } else {
              date_utc = new Date(0); // Epoch start if no date provided
            }
            // dd-mm-yyyy
            const date = date_utc.toLocaleDateString("en-GB", {
              day: "2-digit",
              month: "2-digit",
              year: "numeric",
            });

            posts.push({
              title,
              date_utc,
              date,
              path: `/posts/${entry.name.replace(".html", "")}`,
            });
          } catch (readError) {
            console.error(
              `Error reading or processing file ${entry.name}:`,
              readError,
            );
            continue;
          }
        }
      }

      posts.sort((a, b) => b.date_utc.getTime() - a.date_utc.getTime()); // Sort by date_utc descending

      return renderTemplate("posts_list.html", { posts });
    } catch (error) {
      console.error("Error listing recent posts: ", error);
      set.status = 500;
      set.headers["Content-Type"] = "text/plain";
      return "Internal Server Error";
    }
  });
