import { describe, it, expect } from "vitest";
import { execSync } from "node:child_process";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const CLI = path.join(__dirname, "cli.mjs");

function run(args) {
  try {
    return execSync(`node "${CLI}" ${args}`, { encoding: "utf8" });
  } catch (e) {
    return e.stdout + e.stderr;
  }
}

describe("pnpm work cli", () => {
  it("prints usage when no subcommand is given", () => {
    const out = run("");
    expect(out).toContain("Usage:");
    expect(out).toContain("rebuild-state");
    expect(out).toContain("status");
    expect(out).toContain("next");
    expect(out).toContain("ready");
    expect(out).toContain("blocked");
  });

  it("rebuild-state writes _state.json", () => {
    const out = run("rebuild-state");
    expect(out).toContain("Rebuilt");
    expect(out).toContain("epic");
  });

  it("status prints a tree", () => {
    const out = run("status");
    // We expect at least one epic-line marker character
    expect(out).toMatch(/[✓→○]/);
  });

  it("next prints the next non-done story OR confirms all done", () => {
    const out = run("next");
    expect(out.length).toBeGreaterThan(0);
  });

  it("ready prints something", () => {
    const out = run("ready");
    expect(out.length).toBeGreaterThan(0);
  });

  it("blocked prints something", () => {
    const out = run("blocked");
    expect(out.length).toBeGreaterThan(0);
  });

  it("dispatch prints a plan", () => {
    const out = run("dispatch");
    expect(out).toContain("Dispatch plan");
  });
});
