/**
 * .agents/skills/ directory management
 *
 * Purpose: discover, validate, and load skills from repo-local
 * `.agents/skills/` and user-level skill directories.
 *
 * Consumer: skill loader, auto-skill creation, and model context assembly.
 */
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";

const SKILL_FILENAME = "SKILL.md";
const USER_SKILL_DIR = join(process.env.HOME ?? "", ".sf", "skills");

/**
 * Find all skill directories under a base path.
 */
export function discoverSkillDirs(basePath) {
	const skillRoot = join(basePath, ".agents", "skills");
	if (!existsSync(skillRoot)) return [];

	const dirs = [];
	for (const entry of readdirSync(skillRoot)) {
		const full = join(skillRoot, entry);
		if (statSync(full).isDirectory()) {
			const skillFile = join(full, SKILL_FILENAME);
			if (existsSync(skillFile)) {
				dirs.push({ name: entry, path: full, skillFile });
			}
		}
	}
	return dirs;
}

/**
 * Discover skills from all sources: project, user, and built-in.
 */
export function discoverAllSkills(projectPath) {
	const sources = [];

	// Project skills
	if (projectPath) {
		const projectSkills = discoverSkillDirs(projectPath);
		for (const s of projectSkills) {
			sources.push({ ...s, source: "project" });
		}
	}

	// User skills
	if (existsSync(USER_SKILL_DIR)) {
		const userSkills = discoverSkillDirs(USER_SKILL_DIR);
		for (const s of userSkills) {
			// User skills have a different root structure
			s.path = s.path.replace(/\.agents\/skills$/, "");
			sources.push({ ...s, source: "user" });
		}
	}

	return sources;
}

/**
 * Read the raw content of a skill file.
 */
export function readSkillFile(skillDir) {
	const path = join(skillDir, SKILL_FILENAME);
	if (!existsSync(path)) return null;
	try {
		return readFileSync(path, "utf-8");
	} catch {
		return null;
	}
}
