const express = require("express");
const path = require("path");
const fs = require("fs");

const app = express();

app.use(express.static("public"));

// Set up EJS as the templating engine
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));

// Utility to get directories sorted by datetime
function getSortedReportDirectories(reportDir, env) {
  const dirents = fs
    .readdirSync(reportDir, { withFileTypes: true })
    .filter((dirent) => dirent.isDirectory())
    .map((dirent) => {
      const folderName = dirent.name;
      const parts = folderName.split("-");
      if (parts.length >= 6) {
      const metadata = extractMetadata(folderName);
      const datetime = new Date(`${metadata.date} ${metadata.time}`);
      const link = path.join(env, folderName, "index.html");
      return {
        folderName,
        date: metadata.date,
        time: metadata.time,
        datetime,
        buildId: metadata.buildId,
        link,
      };
    }
    return null;
  })

    .filter(Boolean)
    .sort((a, b) => b.datetime - a.datetime); // Sort in descending order of datetime

  return dirents;
}


// Utility to extract metadata from folder names
function extractMetadata(str) {
  const regex =
    /^([a-z]+)-([a-z]+-[a-z0-9]+)-(\d+)-(\d{4})-(\d{2})-(\d{2})_(\d{2})-(\d{2})-(\d{2})$/;
  const match = str.match(regex);

  if (!match) {
    return "Invalid string format";
  }

  const [_, env, region, buildId, year, month, day, hours, minutes, seconds] =
    match;

  // Create a date object in UTC
  const utcDate = new Date(
    Date.UTC(year, month - 1, day, hours, minutes, seconds)
  );

  // Convert to IST using toLocaleString with the appropriate timezone
  const istDate = utcDate.toLocaleString("en-IN", { timeZone: "Asia/Kolkata" });

  // Separate the date and time from the IST conversion
  const [istDateOnly, istTimeOnly] = istDate.split(", ");

  return {
    env,
    region,
    buildId: parseInt(buildId),
    date: istDateOnly,
    time: istTimeOnly,
    datetime: utcDate,
  };
}

// Route to serve the main index.html
app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "public", "index.html"), (err) => {
    if (err) {
      res.status(err.status).end();
    }
  });
});

// Dynamic route to serve specific folder's index.html for PROD-ASIA-SOUTH1
app.get("/uat-asia-south1/:folderId/index.html", async (req, res) => {
  const folderId = req.params.folderId;
  const reportDir = path.join(
    __dirname,
    "public",
    "uat-asia-south1",
    folderId,
    "index.html"
  );

  // Serve the index.html from the specific folder
  fs.readFile(reportDir, "utf8", (err, data) => {
    if (err) {
      return res
        .status(404)
        .send("Index file not found for the requested folder.");
    }
    res.send(data);
  });
});

// Dynamic route to serve specific folder's index.html for PROD-US-CENTRAL1
app.get("/uat-us-central1/:folderId/index.html", (req, res) => {
  const folderId = req.params.folderId;
  const reportDir = path.join(
    __dirname,
    "public",
    "uat-us-central1",
    folderId,
    "index.html"
  );

  // Serve the index.html from the specific folder
  fs.readFile(reportDir, "utf8", (err, data) => {
    if (err) {
      return res
        .status(404)
        .send("Index file not found for the requested folder.");
    }
    res.send(data);
  });
});
// Dynamic route to serve specific folder's index.html for PROD-ASIA-SOUTH1
app.get("/prod-asia-south1/:folderId/index.html", async (req, res) => {
  const folderId = req.params.folderId;
  const reportDir = path.join(
    __dirname,
    "public",
    "prod-asia-south1",
    folderId,
    "index.html"
  );

  // Serve the index.html from the specific folder
  fs.readFile(reportDir, "utf8", (err, data) => {
    if (err) {
      return res
        .status(404)
        .send("Index file not found for the requested folder.");
    }
    res.send(data);
  });
});

// Dynamic route to serve specific folder's index.html for PROD-US-CENTRAL1
app.get("/prod-us-central1/:folderId/index.html", (req, res) => {
  const folderId = req.params.folderId;
  const reportDir = path.join(
    __dirname,
    "public",
    "prod-us-central1",
    folderId,
    "index.html"
  );

  // Serve the index.html from the specific folder
  fs.readFile(reportDir, "utf8", (err, data) => {
    if (err) {
      return res
        .status(404)
        .send("Index file not found for the requested folder.");
    }
    res.send(data);
  });
});

// Dynamic route to serve specific folder's index.html for DEV-ASIA-SOUTH1
app.get("/dev-asia-south1/:folderId/index.html", (req, res) => {
  const folderId = req.params.folderId;
  const reportDir = path.join(
    __dirname,
    "public",
    "dev-asia-south1",
    folderId,
    "index.html"
  );

  // Serve the index.html from the specific folder
  fs.readFile(reportDir, "utf8", (err, data) => {
    if (err) {
      return res
        .status(404)
        .send("Index file not found for the requested folder.");
    }
    res.send(data);
  });
});

// Dynamic route to serve specific folder's index.html for DEV-US-CENTRAL1
app.get("/dev-us-central1/:folderId/index.html", (req, res) => {
  const folderId = req.params.folderId;
  const reportDir = path.join(
    __dirname,
    "public",
    "dev-us-central1",
    folderId,
    "index.html"
  );

  // Serve the index.html from the specific folder
  fs.readFile(reportDir, "utf8", (err, data) => {
    if (err) {
      return res
        .status(404)
        .send("Index file not found for the requested folder.");
    }
    res.send(data);
  });
});

// Dynamic route for UAT-ASIA-SOUTH1
app.get("/uat-asia", (req, res) => {
  console.log("came here");
  
  const reportDir = path.join(__dirname, "public", "uat-asia-south1");
  const reportDirs = getSortedReportDirectories(reportDir, "uat-asia-south1");
  res.render("reportPage", { reportDirs });
});

// Dynamic route for PROD-US-CENTRAL1 (for all subfolders)
app.get("/uat-us", (req, res) => {
  const reportDir = path.join(__dirname, "public", "uat-us-central1");
  const reportDirs = getSortedReportDirectories(reportDir, "uat-us-central1");
  res.render("reportPage", { reportDirs });
});
// Dynamic route for PROD-ASIA-SOUTH1
app.get("/prod-asia", (req, res) => {
  console.log("came here");
  
  const reportDir = path.join(__dirname, "public", "prod-asia-south1");
  const reportDirs = getSortedReportDirectories(reportDir, "prod-asia-south1");
  res.render("reportPage", { reportDirs });
});

// Dynamic route for PROD-US-CENTRAL1 (for all subfolders)
app.get("/prod-us", (req, res) => {
  const reportDir = path.join(__dirname, "public", "prod-us-central1");
  const reportDirs = getSortedReportDirectories(reportDir, "prod-us-central1");
  res.render("reportPage", { reportDirs });
});

// Dynamic route for DEV-ASIA-SOUTH1
app.get("/dev-asia", (req, res) => {
  const reportDir = path.join(__dirname, "public", "dev-asia-south1");
  const reportDirs = getSortedReportDirectories(reportDir, "dev-asia-south1");
  res.render("reportPage", { reportDirs });
});

// Dynamic route for DEV-US-CENTRAL1
app.get("/dev-us", (req, res) => {
  const reportDir = path.join(__dirname, "public", "dev-us-central1");
  const reportDirs = getSortedReportDirectories(reportDir, "dev-us-central1");
  res.render("reportPage", { reportDirs });
});

// Handle 404 errors
app.use((req, res) => {
  res.status(404).send("404 Not Found");
});

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
