#!/usr/bin/env node
import {
  agentYamlConfigSchema,
  directoryExists,
  formatZodErrors,
  getErrorMessage,
  glob,
  readFile,
  skillFrontmatterLoaderSchema,
  verbose,
  warn
} from "./chunk-LWXRUR6B.js";
import {
  CLAUDE_SRC_DIR,
  DIRS,
  STANDARD_FILES
} from "./chunk-6OWHQ7HM.js";
import {
  init_esm_shims
} from "./chunk-DHET7RCE.js";

// src/cli/lib/loading/loader.ts
init_esm_shims();
import { parse as parseYaml } from "yaml";
import path from "path";
import { unique } from "remeda";
var FRONTMATTER_REGEX = /^---\n([\s\S]*?)\n---/;
function parseFrontmatter(content, filePath) {
  const match = content.match(FRONTMATTER_REGEX);
  if (!match) return null;
  const yamlContent = match[1];
  const parsed = skillFrontmatterLoaderSchema.safeParse(parseYaml(yamlContent));
  if (!parsed.success) {
    const location = filePath ?? "unknown file";
    warn(`Invalid SKILL.md frontmatter in '${location}': ${formatZodErrors(parsed.error.issues)}`);
    return null;
  }
  return parsed.data;
}
async function loadAllAgents(projectRoot) {
  const agents = {};
  const agentSourcesDir = path.join(projectRoot, DIRS.agents);
  const files = await glob(`**/${STANDARD_FILES.AGENT_METADATA_YAML}`, agentSourcesDir);
  for (const file of files) {
    const fullPath = path.join(agentSourcesDir, file);
    try {
      const content = await readFile(fullPath);
      const config = agentYamlConfigSchema.parse(parseYaml(content));
      const agentPath = path.dirname(file);
      agents[config.id] = {
        title: config.title,
        description: config.description,
        model: config.model,
        tools: config.tools,
        path: agentPath,
        sourceRoot: projectRoot,
        ...config.domain ? { domain: config.domain } : {},
        ...config.custom === true ? { custom: true } : {}
      };
      verbose(`Loaded agent: ${config.id} from ${file}`);
    } catch (error) {
      warn(`Skipping invalid metadata.yaml at '${fullPath}': ${getErrorMessage(error)}`);
    }
  }
  return agents;
}
async function loadProjectAgents(projectRoot) {
  const agents = {};
  const projectAgentsDir = path.join(projectRoot, CLAUDE_SRC_DIR, "agents");
  if (!await directoryExists(projectAgentsDir)) {
    verbose(`No project agents directory at ${projectAgentsDir}`);
    return agents;
  }
  const files = await glob(`**/${STANDARD_FILES.AGENT_METADATA_YAML}`, projectAgentsDir);
  for (const file of files) {
    const fullPath = path.join(projectAgentsDir, file);
    try {
      const content = await readFile(fullPath);
      const config = agentYamlConfigSchema.parse(parseYaml(content));
      const agentPath = path.dirname(file);
      agents[config.id] = {
        title: config.title,
        description: config.description,
        model: config.model,
        tools: config.tools,
        path: agentPath,
        sourceRoot: projectRoot,
        agentBaseDir: `${CLAUDE_SRC_DIR}/agents`,
        // Project agents are in .claude-src/agents/
        ...config.domain ? { domain: config.domain } : {}
      };
      verbose(`Loaded project agent: ${config.id} from ${file}`);
    } catch (error) {
      warn(`Skipping invalid metadata.yaml at '${fullPath}': ${getErrorMessage(error)}`);
    }
  }
  return agents;
}
async function buildIdToDirectoryPathMap(skillsDir) {
  const map = {};
  const files = await glob("**/SKILL.md", skillsDir);
  for (const file of files) {
    const fullPath = path.join(skillsDir, file);
    const content = await readFile(fullPath);
    const frontmatter = parseFrontmatter(content, fullPath);
    if (frontmatter?.name) {
      const directoryPath = file.replace("/SKILL.md", "");
      map[frontmatter.name] = directoryPath;
      map[directoryPath] = directoryPath;
    }
  }
  return map;
}
async function loadSkillsByIds(skillIds, projectRoot) {
  const skills = {};
  const skillsDir = path.join(projectRoot, DIRS.skills);
  const idToDirectoryPath = await buildIdToDirectoryPathMap(skillsDir);
  const allSkillIds = Object.keys(idToDirectoryPath);
  const expandedSkillIds = [];
  for (const { id: skillId } of skillIds) {
    if (idToDirectoryPath[skillId]) {
      expandedSkillIds.push(skillId);
    } else {
      const childSkills = allSkillIds.filter((id) => {
        const dirPath = idToDirectoryPath[id];
        return dirPath.startsWith(`${skillId}/`);
      });
      if (childSkills.length > 0) {
        expandedSkillIds.push(...childSkills);
        verbose(`Expanded directory '${skillId}' to ${childSkills.length} skills`);
      } else {
        warn(`Unknown skill reference '${skillId}'`);
      }
    }
  }
  const uniqueSkillIds = unique(expandedSkillIds);
  for (const skillId of uniqueSkillIds) {
    const directoryPath = idToDirectoryPath[skillId];
    if (!directoryPath) {
      warn(`Could not find skill '${skillId}': no matching skill found`);
      continue;
    }
    const skillPath = path.join(skillsDir, directoryPath);
    const skillMdPath = path.join(skillPath, STANDARD_FILES.SKILL_MD);
    try {
      const content = await readFile(skillMdPath);
      const frontmatter = parseFrontmatter(content, skillMdPath);
      if (!frontmatter) {
        warn(`Skipping '${skillId}': missing or invalid frontmatter`);
        continue;
      }
      const canonicalId = frontmatter.name;
      const skillDef = {
        id: canonicalId,
        path: `${DIRS.skills}/${directoryPath}/`,
        description: frontmatter.description
      };
      skills[canonicalId] = skillDef;
      verbose(`Loaded skill: ${canonicalId} (from ${directoryPath})`);
    } catch (error) {
      warn(`Could not load skill '${skillId}': ${error}`);
    }
  }
  return skills;
}
async function loadPluginSkills(pluginDir) {
  const skills = {};
  const pluginSkillsDir = path.join(pluginDir, "skills");
  if (!await directoryExists(pluginSkillsDir)) {
    return skills;
  }
  const files = await glob("**/SKILL.md", pluginSkillsDir);
  for (const file of files) {
    const fullPath = path.join(pluginSkillsDir, file);
    const content = await readFile(fullPath);
    const frontmatter = parseFrontmatter(content, fullPath);
    if (!frontmatter) {
      warn(`Skipping '${file}': missing or invalid frontmatter`);
      continue;
    }
    const folderPath = file.replace("/SKILL.md", "");
    const skillPath = `skills/${folderPath}/`;
    const skillId = frontmatter.name;
    skills[skillId] = {
      id: skillId,
      path: skillPath,
      description: frontmatter.description
    };
    verbose(`Loaded plugin skill: ${skillId} from ${file}`);
  }
  return skills;
}

export {
  parseFrontmatter,
  loadAllAgents,
  loadProjectAgents,
  loadSkillsByIds,
  loadPluginSkills
};
//# sourceMappingURL=chunk-OCEFD7V6.js.map