import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { checkSkillsVersion } from "./skills-version";

describe("checkSkillsVersion", () => {
  let tmpDir: string;

  beforeEach(() => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "skills-version-"));
  });

  afterEach(() => {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  });

  function writeSkill(content: string) {
    const filePath = path.join(tmpDir, ".agents/skills/erp-kit-app-1-requirements/SKILL.md");
    fs.mkdirSync(path.dirname(filePath), { recursive: true });
    fs.writeFileSync(filePath, content);
  }

  it("passes when the recorded version equals the installed version", async () => {
    writeSkill(`---\nmetadata:\n  erp-kit-version: "0.29.0"\n---\n\nbody\n`);
    expect(await checkSkillsVersion(tmpDir, "0.29.0")).toEqual([]);
  });

  it("errors when the recorded version is older", async () => {
    writeSkill(`---\nmetadata:\n  erp-kit-version: "0.27.0"\n---\n\nbody\n`);
    const [finding] = await checkSkillsVersion(tmpDir, "0.29.0");
    expect(finding?.severity).toBe("error");
    expect(finding?.subject).toContain("erp-kit-app-1-requirements/SKILL.md");
    expect(finding?.message).toContain("generated for erp-kit 0.27.0");
    expect(finding?.message).toContain("erp-kit update skills");
  });

  it("surfaces the 0.0.0 placeholder as info", async () => {
    writeSkill(`---\nmetadata:\n  erp-kit-version: "0.0.0"\n---\n\nbody\n`);
    const [finding] = await checkSkillsVersion(tmpDir, "0.29.0");
    expect(finding?.severity).toBe("info");
    expect(finding?.message).toContain("unpublished placeholder");
  });

  it("picks the canonical erp-kit-version key when sibling keys share the suffix", async () => {
    writeSkill(
      `---\nmetadata:\n  published-erp-kit-version: "9.9.9"\n  erp-kit-version: "0.27.0"\n---\n\nbody\n`,
    );
    const [finding] = await checkSkillsVersion(tmpDir, "0.29.0");
    expect(finding?.message).toContain("generated for erp-kit 0.27.0");
  });

  it("errors when the erp-kit-version frontmatter is missing", async () => {
    writeSkill(`---\nmetadata:\n  name: foo\n---\n\nbody\n`);
    const [finding] = await checkSkillsVersion(tmpDir, "0.29.0");
    expect(finding?.severity).toBe("error");
    expect(finding?.message).toContain("metadata.erp-kit-version frontmatter is missing");
  });
});
