const fastify = require("fastify")({
  logger: { level: "error" },
});

const path = require("path");
const jwt = require("jsonwebtoken");
const { initHeadless } = require("./electron/shared/headless");
const { initDatabase } = require("./electron/shared/database");
const { loadExtensions } = require("./electron/shared/extensions");
const { init } = require("./electron/api/rpc/rpc.controller");
const dotenv = require("dotenv");

const isPackaged = process.env.IS_PACKAGED === "true";

const envPath = isPackaged
    ? path.join(process.resourcesPath, ".env")
    : path.join(__dirname, ".env");

dotenv.config({ path: envPath, override: false });
const viewsRoutes = require("./electron/views/views.routes");
const animeRoutes = require("./electron/api/anime/anime.routes");
const booksRoutes = require("./electron/api/books/books.routes");
const proxyRoutes = require("./electron/api/proxy/proxy.routes");
const extensionsRoutes = require("./electron/api/extensions/extensions.routes");
const galleryRoutes = require("./electron/api/gallery/gallery.routes");
const rpcRoutes = require("./electron/api/rpc/rpc.routes");
const userRoutes = require("./electron/api/user/user.routes");
const listRoutes = require("./electron/api/list/list.routes");
const anilistRoute = require("./electron/api/anilist/anilist");

const fs = require("fs");

try {
  console.log("--- DEBUGGING PATHS ---");

  // 1. Check where we are currently running
  console.log("Current Directory:", __dirname);

  // 2. Check if 'electron' exists
  const electronPath = path.join(__dirname, "electron");
  if (fs.existsSync(electronPath)) {
    console.log("✅ electron folder found.");
  } else {
    console.log("❌ electron folder missing!");
  }

  // 3. Check 'electron/api/rpc' specifically
  const rpcPath = path.join(__dirname, "electron", "api", "rpc");
  if (fs.existsSync(rpcPath)) {
    console.log("✅ electron/api/rpc folder found. Contents:");
    // LIST EVERYTHING INSIDE THE RPC FOLDER
    console.log(fs.readdirSync(rpcPath));
  } else {
    console.log(`❌ electron/api/rpc folder NOT found at: ${rpcPath}`);
    // Check parent folder to see what IS there
    const parent = path.join(__dirname, "electron", "api");
    console.log("Contents of electron/api:", fs.readdirSync(parent));
  }
  console.log("-----------------------");
} catch (e) {
  console.log("Debug Error:", e);
}

fastify.addHook("preHandler", async (request) => {
  const auth = request.headers.authorization;
  if (!auth) return;

  try {
    const token = auth.replace("Bearer ", "");
    request.user = jwt.verify(token, process.env.JWT_SECRET);
  } catch (e) {
    return reply.code(401).send({ error: "Invalid token" });
  }
});

fastify.register(require("@fastify/static"), {
  root: path.join(__dirname, "public"),
  prefix: "/public/",
  decorateReply: false,
});

fastify.register(require("@fastify/static"), {
  root: path.join(__dirname, "views"),
  prefix: "/views/",
  decorateReply: false,
});

fastify.register(require("@fastify/static"), {
  root: path.join(__dirname, "src", "scripts"),
  prefix: "/src/scripts/",
  decorateReply: false,
});

fastify.register(viewsRoutes);
fastify.register(animeRoutes, { prefix: "/api" });
fastify.register(booksRoutes, { prefix: "/api" });
fastify.register(proxyRoutes, { prefix: "/api" });
fastify.register(extensionsRoutes, { prefix: "/api" });
fastify.register(galleryRoutes, { prefix: "/api" });
fastify.register(rpcRoutes, { prefix: "/api" });
fastify.register(userRoutes, { prefix: "/api" });
fastify.register(anilistRoute, { prefix: "/api" });
fastify.register(listRoutes, { prefix: "/api" });

const start = async () => {
  try {
    initDatabase("anilist");
    initDatabase("favorites");
    initDatabase("cache");
    initDatabase("userdata");
    init();

    await loadExtensions();

    await fastify.listen({ port: 54322, host: "0.0.0.0" });
    console.log(`Server running at http://localhost:54322`);

    await initHeadless();
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

start();
