import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const definitions = {
  done: `yield* T3.step("work ok", {returns: Schema.Void}, Effect.sleep("3 seconds"));`,
  dur: `yield* T3.step("work ok", {returns: Schema.Void}, Effect.sleep("62 seconds")); yield* T3.sleep("nap", "1 hour");`,
  fail: `yield* T3.step("work fails", {returns: Schema.Void}, Effect.fail("Synthetic failure for retry evidence"));`,
  parallel: `yield* Effect.all([T3.step("parallel one", {returns:Schema.Void}, Effect.sleep("120 seconds")), T3.step("parallel two", {returns:Schema.Void}, Effect.sleep("120 seconds"))], {concurrency:"unbounded"});`,
  quick: `yield* T3.step("first", {returns: Schema.Void}, Effect.sleep("100 millis")); yield* T3.step("second", {returns: Schema.Void}, Effect.sleep("100 millis")); yield* T3.step("third", {returns: Schema.Void}, Effect.sleep("100 millis"));`,
};

test("Workflow durations follow Japanese across totals, rows, sleep, and retry", WEB, async ({t3, app, screen, browser}) => {
  await t3.project("Workflow duration demo");
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    yield* fs.makeDirectory(path.join(T3_HOME, "workflows"), {recursive:true});
    for (const [name, body] of Object.entries(definitions)) {
      yield* fs.writeFileString(path.join(T3_HOME, `workflows/${name}.ts`), `export default T3.workflow("${name}", {version:1,payload:Schema.Struct({})}, Effect.fn(function* () {${body}}));`);
    }
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({patch:{workflowsEnabled:true}});
  }).pipe(Effect.scoped));
  const runs: Record<string,string> = {};
  for (const name of Object.keys(definitions)) {
    const result = await runPromise(makeState(T3_HOME).cli(["workflow", "start", name, "--input", "{}", "--key", `k-${name}`, "--json"]));
    runs[name] = JSON.parse(result.stdout).run.runId;
  }
  await t3.open("/settings/general");
  await screen.getByLabel("Language", {exact:true}).tap();
  await screen.getByText("日本語", {exact:true}).tap();
  await screen.getByLabel("言語", {exact:true}).waitFor();
  const observed: string[] = [];
  for (const name of ["done", "quick", "parallel", "dur", "fail"]) {
    await t3.open(`/workflows?run=${runs[name]}`);
    if (name === "done") await screen.getByText(/所要時間/).waitFor({timeout:30000});
    if (name === "quick") await screen.getByText(/first · second/).waitFor();
    if (name === "parallel") await screen.getByText("parallel two", {exact:true}).first().waitFor();
    if (name === "dur") {
      await screen.getByText("nap", {exact:true}).first().waitFor({timeout:90000});
      await screen.getByText("nap", {exact:true}).first().tap();
    }
    if (name === "fail") await screen.getByText(/後に自動で再試行/).waitFor();
    await app.screenshot(`${name}-japanese-duration`);
    observed.push(await browser.locator("body").textContent() ?? "");
  }
  // Assert after every screen is captured, so both recordings cover the entire reproduction.
  expect(observed.join("\n")).not.toMatch(/\d(?:\.\d+)?[ms](?:\s|$|後|経過|[·])/);
  expect(observed[0]).toMatch(/所要時間 \d(?:\.\d+)?秒/);
  expect(observed[3]).toMatch(/1分2秒/);
  expect(observed[4]).toMatch(/\d+分\d+秒 後に自動で再試行/);
});
