import { BestAgentError } from "@best-agent/foundation";
import type { SkillSummary } from "@best-agent/protocol";
import type { InstalledSkill } from "../contribution/runtime-contribution.js";

export class SkillRegistry {
  readonly #skills = new Map<string, InstalledSkill>();

  constructor(skills: InstalledSkill[]) {
    for (const skill of skills) {
      if (this.#skills.has(skill.id)) {
        throw new BestAgentError("SKILL_CONFLICT", `Skill ${skill.id} is already registered.`);
      }
      this.#skills.set(skill.id, skill);
    }
  }

  get(id: string): InstalledSkill | undefined {
    return this.#skills.get(id);
  }

  require(id: string): InstalledSkill {
    const skill = this.#skills.get(id);
    if (!skill) {
      const available = this.list()
        .map((item) => item.id)
        .join(", ");
      throw new BestAgentError(
        "SKILL_NOT_FOUND",
        `Skill "${id}" not found. Available skills: ${available || "none"}.`,
      );
    }
    return skill;
  }

  list(): SkillSummary[] {
    return Array.from(this.#skills.values()).map((skill) => ({
      allowedTools: skill.allowedTools,
      contextMode: skill.contextMode,
      description: skill.description,
      effort: skill.effort,
      executionMode: skill.executionMode,
      id: skill.id,
      model: skill.model,
      name: skill.name,
      pathScope: skill.pathScope,
      source: skill.source,
      sourceExtension: skill.sourceExtension,
      sourcePlugin: skill.sourcePlugin,
      whenToUse: skill.whenToUse,
    }));
  }
}
