import os from "node:os";
import { Router } from "express";
import { hardwareService } from "../services/hardware.js";

// Unauthenticated — hardware is a property of the machine, not the user. Safe: read-only, no mutation, no secrets.

export function hardwareRoutes(): Router {
  const router = Router();

  router.get("/system/providers", async (_req, res) => {
    try {
      const info = await hardwareService().detect();
      res.json(info);
    } catch {
      // Graceful degradation — return basic info without GPU data
      const totalBytes = os.totalmem();
      const freeBytes = os.freemem();
      const totalGb = Math.round((totalBytes / (1024 * 1024 * 1024)) * 10) / 10;
      const freeGb = Math.round((freeBytes / (1024 * 1024 * 1024)) * 10) / 10;
      const usableGb = Math.round((freeBytes * 0.75) / (1024 * 1024 * 1024) * 10) / 10;
      res.json({
        totalGb,
        freeGb,
        usableGb,
        platform: process.platform,
        gpuName: null,
        gpuVramGb: null,
        unifiedMemory: false,
        hardwareTier: "cpu_only",
        cpuModel: os.cpus()[0]?.model ?? null,
      });
    }
  });

  router.get("/system/providers/recommendation", async (_req, res) => {
    try {
      const { fileURLToPath } = await import("node:url");
      const path = await import("node:path");
      const fs = await import("node:fs");
      const __filename = fileURLToPath(import.meta.url);
      const __dirname = path.dirname(__filename);
      const catalogPath = path.resolve(__dirname, "../data/ollama-model-catalog.json");
      const catalog = JSON.parse(fs.readFileSync(catalogPath, "utf-8")) as {
        models: Array<{
          family: string;
          variants: Array<{ name: string; ramGb: number; vramGb: number; quality: string; tier?: string[] }>;
        }>;
      };

      const hardwareInfo = await hardwareService().detect();

      // Filter catalog entries matching the detected hardware tier
      const recommendedModels = catalog.models.flatMap((family) =>
        family.variants
          .filter((v) => !v.tier || v.tier.includes(hardwareInfo.hardwareTier))
          .map((v) => ({ ...v, family: family.family })),
      );

      res.json({ hardwareInfo, recommendedModels });
    } catch {
      res.status(500).json({ error: "Failed to load hardware recommendations" });
    }
  });

  return router;
}
