/**
 * Skill loader
 *
 * Purpose: load skills from `.agents/skills/` with frontmatter validation,
 * permission checking, and lazy content loading.
 *
 * Consumer: command handlers, auto-dispatch, and model context assembly.
 */
import { discoverAllSkills, readSkillFile } from "./directory.js";
import {
	buildSkillRecord,
	parseSkillFrontmatter,
	validateSkillFrontmatter,
} from "./frontmatter.js";

/**
 * Load all valid skills from all sources.
 *
 * Returns array of skill records with validation errors attached.
 */
export function loadSkills(projectPath) {
	const discovered = discoverAllSkills(projectPath);
	const skills = [];

	for (const { name, path, source } of discovered) {
		const content = readSkillFile(path);
		if (!content) {
			skills.push({
				name,
				source,
				path,
				valid: false,
				errors: ["Could not read SKILL.md"],
			});
			continue;
		}

		const parsed = parseSkillFrontmatter(content);
		if (!parsed) {
			skills.push({
				name,
				source,
				path,
				valid: false,
				errors: ["No YAML frontmatter found"],
			});
			continue;
		}

		const validation = validateSkillFrontmatter(parsed.frontmatter);
		if (!validation.valid) {
			skills.push({
				name,
				source,
				path,
				valid: false,
				errors: validation.errors,
				frontmatter: parsed.frontmatter,
			});
			continue;
		}

		const record = buildSkillRecord(path, parsed.frontmatter, parsed.body);
		skills.push({
			...record,
			source,
			valid: true,
			errors: [],
		});
	}

	return skills;
}

/**
 * Get skills that are safe for the current permission profile.
 */
export function getPermittedSkills(skills, activeProfile) {
	const profileOrder = ["restricted", "normal", "trusted", "unrestricted"];
	const activeIndex = profileOrder.indexOf(activeProfile);
	if (activeIndex === -1) return [];

	return skills.filter((s) => {
		if (!s.valid) return false;
		const skillIndex = profileOrder.indexOf(s.permissionProfile);
		if (skillIndex === -1) return false;
		return skillIndex <= activeIndex;
	});
}

/**
 * Get skills that can be invoked by the model for a given work mode.
 */
export function getModelInvocableSkills(skills, workMode) {
	return skills.filter(
		(s) => s.valid && s.modelInvocable && isSkillRelevant(s, workMode),
	);
}

/**
 * Check if a skill is relevant to the current work mode.
 */
function isSkillRelevant(skill, workMode) {
	if (!skill.triggers || skill.triggers.length === 0) return true;
	return skill.triggers.some(
		(t) =>
			t === workMode ||
			t === "*" ||
			(workMode === "build" && t === "code") ||
			(workMode === "review" && t === "review") ||
			(workMode === "research" && t === "research"),
	);
}
