import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { loadSkillSource, type SkillSource } from "@designpaca/core";

/** 배포물 안에 함께 실린 스킬 원본 위치 (dist/skill) */
export function bundledSkillRoot(): string {
  return fileURLToPath(new URL("./skill", import.meta.url));
}

let cached: SkillSource | null = null;

export async function getSkill(): Promise<SkillSource> {
  if (cached) return cached;
  const root = bundledSkillRoot();
  let version = "0.0.0";
  try {
    version = (await fs.readFile(path.join(root, ".designpaca_version"), "utf8")).trim();
  } catch {
    /* 스탬프가 없으면 0.0.0 으로 두고 진행한다 — 설치 자체를 막을 이유는 없다 */
  }
  cached = await loadSkillSource(root, version);
  return cached;
}

export async function getVersion(): Promise<string> {
  return (await getSkill()).version;
}
