import { readFile } from "node:fs/promises";
import { join } from "node:path";

const SKILLS_DIR =
  process.env.SKILLS_DIR || "/Users/teletranone/teletraan/skills";
const REGISTRY_PATH = join(SKILLS_DIR, "registry.json");

interface SkillEntry {
  name: string;
  description: string;
  version: string;
  file: string;
  allowedTools: string[];
  agents: string[];
}

interface Registry {
  skills: Record<string, SkillEntry>;
  mcpServers: Record<string, unknown>;
}

let cachedContent: string | null = null;

export async function loadSkills(agentName: string): Promise<string> {
  let registry: Registry;
  try {
    const raw = await readFile(REGISTRY_PATH, "utf-8");
    registry = JSON.parse(raw) as Registry;
  } catch {
    return "# No skills registered\n";
  }

  const assignedSkills = Object.values(registry.skills).filter((s) =>
    s.agents.includes(agentName)
  );

  if (assignedSkills.length === 0) {
    return "# No skills assigned to this agent\n";
  }

  const sections: string[] = [];

  for (const skill of assignedSkills) {
    try {
      const content = await readFile(join(SKILLS_DIR, skill.file), "utf-8");
      sections.push(
        `<!-- skill: ${skill.name} -->\n# ${skill.name} (v${skill.version})\n\n${content}\n\n---`
      );
    } catch {
      sections.push(
        `<!-- skill: ${skill.name} -->\n# ${skill.name} (v${skill.version})\n\n*Skill file not found: ${skill.file}*\n\n---`
      );
    }
  }

  return sections.join("\n\n");
}

export async function reloadSkillsCache(agentName: string): Promise<void> {
  cachedContent = await loadSkills(agentName);
}

export async function getCachedSkills(agentName: string): Promise<string> {
  if (cachedContent === null) {
    cachedContent = await loadSkills(agentName);
  }
  return cachedContent;
}

export function invalidateCache(): void {
  cachedContent = null;
}
