import os from "node:os";
import { Router } from "express";
import { assertCompanyAccess } from "./authz.js";
import { detectOllama, listOllamaModels, getRecommendedModel } from "../services/ollama.js";

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

  // GET /companies/:companyId/ollama/status
  router.get("/companies/:companyId/ollama/status", async (req, res) => {
    const { companyId } = req.params;
    try {
      assertCompanyAccess(req, companyId);
      const status = await detectOllama();
      res.json(status);
    } catch (err: unknown) {
      if (err && typeof err === "object" && "statusCode" in err) {
        const e = err as { statusCode: number; message: string };
        res.status(e.statusCode).json({ error: e.message });
        return;
      }
      res.status(500).json({ error: "Unexpected error" });
    }
  });

  // GET /companies/:companyId/ollama/models
  router.get("/companies/:companyId/ollama/models", async (req, res) => {
    const { companyId } = req.params;
    try {
      assertCompanyAccess(req, companyId);

      const status = await detectOllama();
      if (!status.installed) {
        res.json({ models: [], ramGb: 0 });
        return;
      }

      const models = await listOllamaModels();
      const enrichedModels = getRecommendedModel(models, os.totalmem());
      const ramGb = Math.round(os.totalmem() / 1073741824);

      res.json({ models: enrichedModels, ramGb });
    } catch (err: unknown) {
      if (err && typeof err === "object" && "statusCode" in err) {
        const e = err as { statusCode: number; message: string };
        res.status(e.statusCode).json({ error: e.message });
        return;
      }
      res.status(500).json({ error: "Unexpected error" });
    }
  });

  return router;
}
