import { describe, it, expect, beforeEach, afterEach } from "bun:test";
import { initDb, closeDb, getDb } from "../store/db";
import {
  acquirePipelineLock,
  markRunFailed,
  incrementResumeAttempts,
  getPipelineRun,
  createPipelineStep,
  updatePipelineStep,
  getStepsForRun,
} from "./store";
import {
  resumeRunById,
  resumeAllInterrupted,
  resumeInterruptedRuns,
  type PipelineDispatcher,
} from "./resume";
import { beginRun, __resetActiveRuns } from "./active-runs";
import type { PipelineConfig } from "./types";

const TEST_PIPELINE = "test-resume-by-id";

async function cleanup(): Promise<void> {
  const db = getDb();
  await db.unsafe(
    `DELETE FROM pipeline_steps WHERE run_id IN
       (SELECT id FROM pipeline_runs WHERE pipeline_id = $1)`,
    [TEST_PIPELINE],
  );
  await db.unsafe(`DELETE FROM pipeline_runs WHERE pipeline_id = $1`, [
    TEST_PIPELINE,
  ]);
}

/** A dispatcher spy that records its calls and never fires a real pipeline. */
function spyDispatcher(): {
  fn: PipelineDispatcher;
  calls: Array<{ pipelineId: string; config: PipelineConfig; runId: string }>;
} {
  const calls: Array<{ pipelineId: string; config: PipelineConfig; runId: string }> = [];
  const fn: PipelineDispatcher = async (pipelineId, config, runId) => {
    calls.push({ pipelineId, config, runId });
    return undefined;
  };
  return { fn, calls };
}

describe("resumeRunById", () => {
  beforeEach(async () => {
    await initDb(process.env.DATABASE_URL);
    __resetActiveRuns();
    await cleanup();
  });

  afterEach(async () => {
    await cleanup();
    await closeDb();
  });

  it("returns not_found and does not dispatch for an unknown run id", async () => {
    const spy = spyDispatcher();
    const result = await resumeRunById(crypto.randomUUID(), null, spy.fn);
    expect(result.ok).toBe(false);
    if (!result.ok) expect(result.reason).toBe("not_found");
    expect(spy.calls).toHaveLength(0);
  });

  it("re-dispatches a failed run with its stored config and resets state", async () => {
    const { runId } = await acquirePipelineLock(TEST_PIPELINE);
    // Drive it into a failed state with a spent resume budget, like a run that
    // exhausted auto-resume.
    await incrementResumeAttempts(runId!);
    await incrementResumeAttempts(runId!);
    await markRunFailed(runId!, "Exceeded max resume attempts (3)");

    const spy = spyDispatcher();
    const result = await resumeRunById(runId!, null, spy.fn);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.runId).toBe(runId!);
      expect(result.pipelineId).toBe(TEST_PIPELINE);
    }

    // Dispatched exactly once, with this run's id + pipeline.
    expect(spy.calls).toHaveLength(1);
    expect(spy.calls[0]!.runId).toBe(runId!);
    expect(spy.calls[0]!.pipelineId).toBe(TEST_PIPELINE);

    // Run reset to running, error cleared, attempt cap reset, finish time cleared.
    const run = await getPipelineRun(runId!);
    expect(run!.status).toBe("running");
    expect(run!.error).toBeNull();
    expect(run!.finishedAt).toBeNull();
    const resumable = (await getDb()`
      SELECT resume_attempts FROM pipeline_runs WHERE id = ${runId!}
    `) as Array<{ resume_attempts: number }>;
    expect(Number(resumable[0]!.resume_attempts)).toBe(0);
  });
});

describe("resumeAllInterrupted", () => {
  beforeEach(async () => {
    await initDb(process.env.DATABASE_URL);
    __resetActiveRuns();
    await cleanup();
  });

  afterEach(async () => {
    await cleanup();
    await closeDb();
  });

  it("re-dispatches every interrupted ('running') run, not the failed ones", async () => {
    const a = await acquirePipelineLock(TEST_PIPELINE); // running
    const b = await acquirePipelineLock(TEST_PIPELINE); // running
    const dead = await acquirePipelineLock(TEST_PIPELINE);
    await markRunFailed(dead.runId!, "real failure");

    const spy = spyDispatcher();
    const count = await resumeAllInterrupted(null, spy.fn);

    const dispatchedIds = spy.calls.map((c) => c.runId);
    // Membership (the shared DB may hold other 'running' rows): both of ours
    // were dispatched, the genuinely-failed one was not.
    expect(dispatchedIds).toContain(a.runId!);
    expect(dispatchedIds).toContain(b.runId!);
    expect(dispatchedIds).not.toContain(dead.runId!);
    expect(count).toBeGreaterThanOrEqual(2);
  });
});

describe("duplicate-dispatch guard", () => {
  beforeEach(async () => {
    await initDb(process.env.DATABASE_URL);
    __resetActiveRuns();
    await cleanup();
  });

  afterEach(async () => {
    __resetActiveRuns();
    await cleanup();
    await closeDb();
  });

  it("resumeRunById refuses a run already active in THIS process (no dispatch)", async () => {
    const { runId } = await acquirePipelineLock(TEST_PIPELINE);
    // Simulate the run already executing here (runIdeasPipeline calls beginRun).
    beginRun(runId!);

    const spy = spyDispatcher();
    const result = await resumeRunById(runId!, null, spy.fn);

    expect(result.ok).toBe(false);
    if (!result.ok) expect(result.reason).toBe("already_running");
    expect(spy.calls).toHaveLength(0);
  });

  it("resumeRunById refuses a run kept alive by a fresh step heartbeat (cross-process)", async () => {
    const { runId } = await acquirePipelineLock(TEST_PIPELINE);
    // A 'running' step created just now carries a fresh heartbeat — another
    // process is actively executing this run.
    await createPipelineStep({ runId: runId!, stepName: "synthesis" });

    const spy = spyDispatcher();
    const result = await resumeRunById(runId!, null, spy.fn);

    expect(result.ok).toBe(false);
    if (!result.ok) expect(result.reason).toBe("already_running");
    expect(spy.calls).toHaveLength(0);
  });

  it("resumeRunById proceeds when the heartbeat has gone stale (interrupted, dead)", async () => {
    const { runId } = await acquirePipelineLock(TEST_PIPELINE);
    const step = await createPipelineStep({ runId: runId!, stepName: "synthesis" });
    // Age the heartbeat past the live window — the writer process is gone.
    await getDb().unsafe(
      `UPDATE pipeline_steps SET last_heartbeat = last_heartbeat - 600 WHERE id = $1`,
      [step.id],
    );

    const spy = spyDispatcher();
    const result = await resumeRunById(runId!, null, spy.fn);

    expect(result.ok).toBe(true);
    expect(spy.calls).toHaveLength(1);
    expect(spy.calls[0]!.runId).toBe(runId!);
  });

  it("resumeInterruptedRuns (boot) resumes a recently-interrupted run despite a fresh heartbeat", async () => {
    const { runId } = await acquirePipelineLock(TEST_PIPELINE);
    // Fast-restart shape: a 'running' step whose heartbeat is still fresh, left
    // by the process that just died. The in-process registry is empty (fresh
    // boot), so the run IS dead and MUST be resumed — trusting the dead
    // process's heartbeat here is the bug that orphaned runs across a quick
    // restart. Boot-resume relies on the registry, never the heartbeat.
    await createPipelineStep({ runId: runId!, stepName: "synthesis" });
    __resetActiveRuns();

    const spy = spyDispatcher();
    await resumeInterruptedRuns(null, spy.fn);

    expect(spy.calls.map((c) => c.runId)).toContain(runId!);
  });

  it("resumeAllInterrupted skips a live run and does not dispatch it", async () => {
    const live = await acquirePipelineLock(TEST_PIPELINE);
    const dead = await acquirePipelineLock(TEST_PIPELINE);
    beginRun(live.runId!); // live is executing in this process

    const spy = spyDispatcher();
    await resumeAllInterrupted(null, spy.fn);

    const dispatchedIds = spy.calls.map((c) => c.runId);
    expect(dispatchedIds).not.toContain(live.runId!);
    expect(dispatchedIds).toContain(dead.runId!);
  });
});

describe("ghost step reconcile on resume", () => {
  beforeEach(async () => {
    await initDb(process.env.DATABASE_URL);
    __resetActiveRuns();
    await cleanup();
  });

  afterEach(async () => {
    __resetActiveRuns();
    await cleanup();
    await closeDb();
  });

  it("resumeRunById fails dangling running steps before re-dispatch, preserving completed", async () => {
    const { runId } = await acquirePipelineLock(TEST_PIPELINE);

    // Simulate prior run: landscape completed, reviews still 'running' (ghost from prior process).
    const comp = await createPipelineStep({ runId: runId!, stepName: "landscape" });
    await updatePipelineStep(comp.id, {
      status: "completed",
      outputSummary: "done",
      outputJson: { ok: true },
    });
    await createPipelineStep({ runId: runId!, stepName: "reviews" }); // ghost

    // Age the heartbeat so isRunLive does not short-circuit (run is treated as dead).
    await getDb().unsafe(
      `UPDATE pipeline_steps SET last_heartbeat = last_heartbeat - 600 WHERE run_id = $1`,
      [runId!],
    );

    const spy = spyDispatcher();
    const result = await resumeRunById(runId!, null, spy.fn);

    expect(result.ok).toBe(true);

    const steps = await getStepsForRun(runId!);
    const byName = new Map(steps.map((s) => [s.stepName, s]));

    // Completed checkpoint must survive (runStep will replay it).
    expect(byName.get("landscape")!.status).toBe("completed");
    // Ghost must be failed.
    expect(byName.get("reviews")!.status).toBe("failed");
    // Dispatcher was called exactly once.
    expect(spy.calls).toHaveLength(1);
    expect(spy.calls[0]!.runId).toBe(runId!);
  });

  it("resumeInterruptedRuns fails dangling running steps before re-dispatch", async () => {
    const { runId } = await acquirePipelineLock(TEST_PIPELINE);

    const ghost = await createPipelineStep({ runId: runId!, stepName: "synthesis" });
    // Age the heartbeat so resumeInterruptedRuns won't skip (it uses registry-only check anyway)
    await getDb().unsafe(
      `UPDATE pipeline_steps SET last_heartbeat = last_heartbeat - 600 WHERE id = $1`,
      [ghost.id],
    );

    __resetActiveRuns();
    const spy = spyDispatcher();
    await resumeInterruptedRuns(null, spy.fn);

    const steps = await getStepsForRun(runId!);
    const synthStep = steps.find((s) => s.stepName === "synthesis");
    expect(synthStep!.status).toBe("failed");
    expect(spy.calls.map((c) => c.runId)).toContain(runId!);
  });
});
