import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import type { Factory } from "@jigs-ai/jigs";
import { expect, test } from "vitest";
import factory from "./jigs.config.ts";

const workflows: Factory["workflows"] = Object.fromEntries(
  await Promise.all(
    Object.entries(factory.workflows).map(async ([name, load]) => [name, (await load()).default]),
  ),
);

test("every entry carries a zod inputs schema and a workflow", () => {
  expect(Object.keys(workflows)).toContain("hello");
  for (const entry of Object.values(workflows)) {
    expect(entry.inputs.safeParse).toBeTypeOf("function");
    expect(entry.workflow).toBeTypeOf("function");
  }
});

// Inspect compiled IDs; source imports do not determine the emitted addresses.

const BUNDLE = new URL("./.output/server/index.mjs", import.meta.url);

function emittedIds(): string[] {
  let bundle: string;
  try {
    bundle = readFileSync(BUNDLE, "utf8");
  } catch {
    throw new Error(
      `no build at ${fileURLToPath(BUNDLE)} to read ids from — run pnpm exec jigs build first`,
    );
  }
  return [
    ...new Set(
      (bundle.match(/"(?:workflow|step)\/\/[^"]+"/g) ?? [])
        .map((id) => id.slice(1, -1))
        .filter((id) => /^(?:workflow|step)\/\/\.\/(?!node_modules\/)/.test(id)),
    ),
  ].sort();
}

test("no emitted factory id carries a package version", () => {
  expect(emittedIds().filter((id) => id.includes("@"))).toEqual([]);
});

test("every id this factory owns is addressed by a path inside it", () => {
  const owned = emittedIds();
  expect(owned.length).toBeGreaterThan(0);
  for (const id of owned) {
    expect(id).toMatch(/^(?:workflow|step)\/\/\.\/(?:workflows|\.jigs)\//);
  }
});

test("every workflow this factory registers emitted a workflow id", () => {
  const emitted = emittedIds().filter((id) => id.startsWith("workflow//"));
  expect(emitted).toHaveLength(Object.keys(workflows).length);
});
