import fs from "fs";
import matter from "gray-matter";
import path from "path";

export type FaqItem = {
  question: string;
  answer: string;
};

export type FaqSection = {
  title: string;
  subtitle: string;
  order: number;
  items: FaqItem[];
};

function getFaqContentDir(): string {
  const cwd = process.cwd();
  const direct = path.join(cwd, "content", "faq");
  if (fs.existsSync(direct)) return direct;
  const fromStorefront = path.join(cwd, "apps", "storefront", "content", "faq");
  if (fs.existsSync(fromStorefront)) return fromStorefront;
  return direct;
}

/**
 * Parses FAQ markdown body: each "### Question" heading starts a new Q&A;
 * the following lines (until the next ### or EOF) are the answer.
 */
function parseFaqBody(body: string): FaqItem[] {
  const trimmed = body.trim();
  if (!trimmed) return [];

  const blocks = trimmed.split(/\n(?=### )/);
  const items: FaqItem[] = [];

  for (const block of blocks) {
    const firstNewline = block.indexOf("\n");
    const firstLine = firstNewline === -1 ? block : block.slice(0, firstNewline);
    const rest = firstNewline === -1 ? "" : block.slice(firstNewline + 1).trim();
    const question = firstLine.replace(/^###\s*/, "").trim();
    if (question) {
      items.push({ question, answer: rest });
    }
  }

  return items;
}

/**
 * Reads and parses all FAQ section markdown files. Server-only; use in Server Components.
 * Returns sections sorted by frontmatter `order`.
 */
export function getFaqSections(): FaqSection[] {
  const contentDir = getFaqContentDir();
  if (!fs.existsSync(contentDir)) return [];

  const files = fs.readdirSync(contentDir).filter((f) => f.endsWith(".md"));
  const sections: FaqSection[] = [];

  for (const file of files) {
    const filePath = path.join(contentDir, file);
    try {
      const raw = fs.readFileSync(filePath, "utf-8");
      const { data, content } = matter(raw);
      const title = (data.title as string) ?? path.basename(file, ".md");
      const subtitle = (data.subtitle as string) ?? "";
      const order = typeof data.order === "number" ? data.order : 999;
      const items = parseFaqBody(content);
      sections.push({ title, subtitle, order, items });
    } catch {
      // skip invalid files
    }
  }

  sections.sort((a, b) => a.order - b.order);
  return sections;
}
