import fs from 'node:fs/promises';
import path from 'node:path';
import { getSkillsDir } from './paths.js';

const HIDDEN_TYPES = new Set(['private', 'tmp']);

export async function parseVersions({ includeHidden = false } = {}) {
  const skillsDir = getSkillsDir();
  let entries;
  try {
    entries = await fs.readdir(skillsDir, { withFileTypes: true });
  } catch {
    return [];
  }

  const skills = [];
  for (const entry of entries) {
    if (!entry.isDirectory()) continue;
    const jsonPath = path.join(skillsDir, entry.name, 'skill.json');
    try {
      const raw = await fs.readFile(jsonPath, 'utf-8');
      const data = JSON.parse(raw);
      const types = data.types || [];
      if (!includeHidden && types.some((t) => HIDDEN_TYPES.has(t))) continue;
      skills.push({
        name: data.name || entry.name,
        version: data.version || '0.0.0',
        types,
        displayName: data.displayName || '',
        description: data.description || '',
      });
    } catch {
      // skip directories without valid skill.json
    }
  }

  return skills.sort((a, b) => a.name.localeCompare(b.name));
}

export async function findSkill(skillName, { includeHidden = false } = {}) {
  const skills = await parseVersions({ includeHidden });
  return skills.find((s) => s.name === skillName) || null;
}

export async function getSkillDetail(skillName, { includeHidden = false } = {}) {
  const jsonPath = path.join(getSkillsDir(), skillName, 'skill.json');
  let raw;
  try {
    raw = await fs.readFile(jsonPath, 'utf-8');
  } catch {
    return null;
  }
  const data = JSON.parse(raw);
  const types = data.types || [];
  if (!includeHidden && types.some((t) => HIDDEN_TYPES.has(t))) return null;
  return data;
}
