import { createLogger } from "@lib/log.ts";
import { join } from "node:path";
import { DATA_DIR } from "@lib/env.ts";
import { ensureDir } from "fs";

function getLogFileName() {
  const d = new Date();
  const year = d.getFullYear();
  const month = (d.getMonth() + 1).toString().padStart(2, "0"); // Ensure two digits
  const day = d.getDate().toString().padStart(2, "0"); // Ensure two digits
  return `${year}-${month}-${day}.log`;
}

const LOG_DIR = join(DATA_DIR, "logs");

// Ensure the log directory exists
await ensureDir(LOG_DIR);

const log = createLogger("");
log.addEventListener("log", async (data) => {
  const logEntry = JSON.stringify(data.detail);
  const logFilePath = join(LOG_DIR, getLogFileName());

  // Append the log entry to the file (creating it if it doesn't exist)
  await Deno.writeTextFile(
    logFilePath,
    new Date().toISOString() + " | " + logEntry + "\n",
    { append: true },
  );
});

export type Log = {
  scope: string;
  level: number;
  date: Date;
  args: unknown[];
};

export async function getLogs() {
  const logFilePath = join(LOG_DIR, getLogFileName());

  try {
    // Read the log file content
    const logFileContent = await Deno.readTextFile(logFilePath);

    // Split by lines and parse logs
    const logs: Log[] = logFileContent
      .split("\n")
      .filter((line) => line.trim() !== "")
      .map((line) => {
        const [date, ...rest] = line.split(" | ");
        const parsed = JSON.parse(rest.join(" | ")) as Log;
        return {
          ...parsed,
          date: new Date(date),
        } as Log;
      });
    console.log(logs);

    // Return the logs sorted by date
    return logs.sort((a, b) => a.date.getTime() - b.date.getTime());
  } catch (error) {
    // If file does not exist, return an empty array
    return [];
  }
}
