import { promises as fs } from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const projectsFile = path.resolve(__dirname, "../../data/projects.json");

const AI_CHATBOT_PROJECT = {
  id: "ai-chatbot",
  title: "AI Chatbot",
  summary: "Conversational assistant demo with retrieval-oriented context grounding",
  phase: "Phase I: Internal Integration",
  lead: "Truc NNguyen",
  scope: "ColdBrewNLP",
  actionLabel: "View details",
  actionUrl: "/projects/ai-chatbot",
};

function ensureAiChatbotProject(projects) {
  const directory = projects && typeof projects === "object" ? { ...projects } : {};
  const ongoing = Array.isArray(directory.ongoing) ? [...directory.ongoing] : [];
  const hasAiChatbot = ongoing.some((item) => item?.id === AI_CHATBOT_PROJECT.id);

  if (!hasAiChatbot) ongoing.unshift(AI_CHATBOT_PROJECT);

  const activeIndex = Array.isArray(directory.stats)
    ? directory.stats.findIndex((stat) => String(stat?.label || "").toLowerCase() === "active")
    : -1;

  if (activeIndex >= 0) {
    const currentValue = Number(directory.stats[activeIndex]?.value || ongoing.length);
    directory.stats = [...directory.stats];
    directory.stats[activeIndex] = {
      ...directory.stats[activeIndex],
      value: String(Math.max(currentValue, ongoing.length)),
    };
  }

  return {
    ...directory,
    ongoing,
  };
}

export async function getProjectsDirectory() {
  const raw = await fs.readFile(projectsFile, "utf8");
  const parsed = JSON.parse(raw);
  return ensureAiChatbotProject(parsed);
}
