import { describe, expect, it } from "vitest";

const { formatSummary, parseWaitSeconds, validatePreflight } = require("../../scripts/live-preflight.cjs") as {
  formatSummary: (result: unknown) => string;
  parseWaitSeconds: (value: string) => number;
  validatePreflight: (input: unknown) => { ok: boolean; errors: string[]; signature: string; isElevated?: boolean; genshinFound?: boolean };
};

function health(signature = "sig-current") {
  return { ok: true, appBuild: { signature } };
}

function status(runtime = { isElevated: true, genshinFound: true, targetProcess: "GenshinImpact.exe", foregroundProcess: "GenshinImpact.exe" }) {
  return { ok: true, status: { runtimeInfo: runtime } };
}

describe("live preflight script", () => {
  it("accepts a matching elevated Genshin runtime", () => {
    const result = validatePreflight({ health: health(), status: status(), expected: "sig-current" });
    expect(result.ok).toBe(true);
    expect(result.errors).toEqual([]);
    expect(result.signature).toBe("sig-current");
  });

  it("rejects stale runtime signatures", () => {
    const result = validatePreflight({ health: health("old"), status: status(), expected: "sig-current" });
    expect(result.ok).toBe(false);
    expect(result.errors.join("\n")).toContain("does not match");
  });

  it("rejects non-elevated or missing Genshin runtime by default", () => {
    const result = validatePreflight({
      health: health(),
      status: status({ isElevated: false, genshinFound: false, targetProcess: "", foregroundProcess: "explorer.exe" }),
      expected: "sig-current",
    });
    expect(result.ok).toBe(false);
    expect(result.errors).toContain("Runtime is not elevated.");
    expect(result.errors).toContain("Genshin process/window was not found.");
  });

  it("formats a concise human summary", () => {
    const summary = formatSummary(validatePreflight({ health: health(), status: status(), expected: "sig-current" }));
    expect(summary).toContain("live preflight: PASS");
    expect(summary).toContain("elevated: yes");
    expect(summary).toContain("genshin: yes");
  });

  it("parses optional wait seconds strictly", () => {
    expect(parseWaitSeconds("")).toBe(0);
    expect(parseWaitSeconds("120")).toBe(120);
    expect(() => parseWaitSeconds("-1")).toThrow("--wait");
    expect(() => parseWaitSeconds("1.5")).toThrow("--wait");
    expect(() => parseWaitSeconds("soon")).toThrow("--wait");
  });
});
