// Helpers for the manager page. Backed by live API via api-client.jsx —
// the previous hardcoded INITIAL_SKILLS / INITIAL_MCPS arrays are gone;
// data flows in via window.api.{listSkills, listMcpServers} at mount.

const SKILL_TEMPLATE_MD = `---
name: {name}
description: {desc}
---

# {name}

{desc}

## When to use

Describe the situations where this skill should be invoked.

## How to use

1. Step one
2. Step two
3. Step three

## Examples

\`\`\`
example usage…
\`\`\`
`;

// Empty starter arrays so the editors don't blow up on first render before
// the API resolves; manage-app.jsx overwrites with real data.
const INITIAL_SKILLS = [];
const INITIAL_MCPS = [];

// File-tree helpers — still used by the Skill editor for the directory tree
// even though the backend currently only persists SKILL.md text.
function langFor(path) {
  const ext = path.split(".").pop().toLowerCase();
  return ({
    md: "markdown",
    py: "python",
    js: "javascript",
    jsx: "jsx",
    ts: "typescript",
    json: "json",
    sql: "sql",
    txt: "text",
    yml: "yaml",
    yaml: "yaml",
    html: "html",
    css: "css",
    sh: "shell",
  })[ext] || "text";
}

function buildTree(files) {
  const root = { name: "", isDir: true, path: "", children: [] };
  (files || []).forEach((f) => {
    const parts = f.path.split("/");
    let cur = root;
    for (let i = 0; i < parts.length; i++) {
      const part = parts[i];
      const isLast = i === parts.length - 1;
      const subPath = parts.slice(0, i + 1).join("/");
      let next = cur.children.find((c) => c.name === part);
      if (!next) {
        next = isLast
          ? { name: part, isDir: false, path: subPath, file: f }
          : { name: part, isDir: true, path: subPath, children: [] };
        cur.children.push(next);
      }
      cur = next;
    }
  });
  const sortRec = (node) => {
    if (!node.isDir) return;
    node.children.sort((a, b) => {
      if (a.name === "SKILL.md") return -1;
      if (b.name === "SKILL.md") return 1;
      if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
      return a.name.localeCompare(b.name);
    });
    node.children.forEach(sortRec);
  };
  sortRec(root);
  return root;
}

Object.assign(window, {
  SKILL_TEMPLATE_MD,
  INITIAL_SKILLS,
  INITIAL_MCPS,
  langFor,
  buildTree,
});
