import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { parse } from "yaml";
import { envString } from "../env.js";

export type SkillDefinition = {
  id: string;
  name: string;
  description: string;
  enabled: boolean;
  prompt: string;
};

export type PublicSkillDefinition = Omit<SkillDefinition, "prompt">;

type SkillsFile = { skills?: SkillDefinition[] };

const defaultPath = (): string => {
  // When the API is started from apps/api, the config dir is at ../../config.
  // The env var wins so tests / docker setups can override.
  return envString(process.env.SKILLS_CONFIG_PATH, resolve(process.cwd(), "../../config/skills.yml"));
};

export const loadSkillDefinitions = (
  configPath: string = defaultPath(),
): SkillDefinition[] => {
  try {
    const raw = readFileSync(configPath, "utf8");
    const parsed = parse(raw) as SkillsFile;
    if (!parsed || !Array.isArray(parsed.skills)) return [];
    return parsed.skills
      .filter((skill) => skill && typeof skill === "object")
      .map((skill) => ({
        id: String(skill.id ?? "").trim(),
        name: String(skill.name ?? "").trim(),
        description: String(skill.description ?? "").trim(),
        enabled: Boolean(skill.enabled),
        prompt: String(skill.prompt ?? "").trim(),
      }))
      .filter((skill) => skill.id.length > 0);
  } catch (error) {
    // Config is optional: missing file is fine, malformed file should surface.
    const code = (error as NodeJS.ErrnoException).code;
    if (code === "ENOENT") return [];
    throw error;
  }
};

export const getEnabledSkillPrompts = (skills: SkillDefinition[] = loadSkillDefinitions()): string[] =>
  skills.filter((skill) => skill.enabled && skill.prompt.length > 0).map((skill) => skill.prompt);

export const toPublicSkill = (skill: SkillDefinition): PublicSkillDefinition => ({
  id: skill.id,
  name: skill.name,
  description: skill.description,
  enabled: skill.enabled,
});
