import test from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
	nextLocalMidnightMs,
	isInRestartWarningWindow,
	restartWarningStartsAt,
	formatRestartCountdown,
	restartCountdownMessage,
	RESTART_WARN_BEFORE_MS
} from "../../shared/deploy/schedule.js";
import { DeployScheduler } from "../src/deploy/scheduler.js";
import {
	writeRestartManifest,
	readRestartManifest,
	consumeRestartManifest,
	restartManifestPath
} from "../src/deploy/manifest.js";

test("nextLocalMidnightMs is the following calendar midnight", () =>
{
	const noon = new Date(2026, 7, 27, 12, 0, 0, 0).getTime();
	const midnight = nextLocalMidnightMs(noon);
	const d = new Date(midnight);
	assert.equal(d.getFullYear(), 2026);
	assert.equal(d.getMonth(), 7);
	assert.equal(d.getDate(), 28);
	assert.equal(d.getHours(), 0);
	assert.equal(d.getMinutes(), 0);
});

test("warning window stays open for the whole scheduled period", () =>
{
	const scheduledAt = new Date(2026, 7, 28, 0, 0, 0, 0).getTime();
	assert.equal(restartWarningStartsAt(scheduledAt), 0);
	assert.equal(isInRestartWarningWindow(scheduledAt - RESTART_WARN_BEFORE_MS, scheduledAt), true);
	assert.equal(isInRestartWarningWindow(scheduledAt - RESTART_WARN_BEFORE_MS - 1, scheduledAt), true);
	assert.equal(isInRestartWarningWindow(scheduledAt - 12 * 60 * 60 * 1000, scheduledAt), true);
	assert.equal(isInRestartWarningWindow(scheduledAt, scheduledAt), false);
});

test("countdown formatting", () =>
{
	assert.equal(formatRestartCountdown(45_000), "45s");
	assert.equal(formatRestartCountdown(125_000), "2m 05s");
	assert.match(restartCountdownMessage(3_600_000), /1h 00m 00s/);
	const scheduledAt = Date.now() + 90_000;
	assert.match(
		restartCountdownMessage(Math.max(0, scheduledAt - Date.now())),
		/1m \d{2}s/
	);
});

test("restart manifest write read consume is atomic-ish", () =>
{
	const dir = mkdtempSync(join(tmpdir(), "mmo-restart-"));
	const path = restartManifestPath(dir);
	writeRestartManifest(path, {
		reasons: ["code-update"],
		deployCode: true,
		targetCommit: "abc",
		writtenAt: 123
	});
	assert.equal(existsSync(path), true);
	const read = readRestartManifest(path);
	assert.equal(read.deployCode, true);
	assert.equal(read.targetCommit, "abc");
	const consumed = consumeRestartManifest(path);
	assert.equal(consumed.deployCode, true);
	assert.equal(existsSync(path), false);
	assert.equal(consumeRestartManifest(path), null);
});

test("DeployScheduler schedules only when remote is ahead", async () =>
{
	let now = new Date(2026, 7, 27, 12, 0, 0, 0).getTime();
	const statuses = [];
	let ahead = true;
	const scheduler = new DeployScheduler({
		repoRoot: ".",
		enabled: true,
		now: () => now,
		checkIntervalMs: 60_000,
		checkRemote: async () => ({
			ok: true,
			ahead,
			local: "aaa",
			remote: ahead ? "bbb" : "aaa"
		}),
		onStatusChange (status)
		{ statuses.push(status); }
	});
	await scheduler.poll();
	assert.equal(scheduler.status().scheduled, true);
	assert.equal(scheduler.status().scheduledAt, nextLocalMidnightMs(now));
	assert.equal(scheduler.status().warning, true);

	now = scheduler.status().scheduledAt - RESTART_WARN_BEFORE_MS;
	scheduler.tick();
	assert.equal(scheduler.status().warning, true);

	ahead = false;
	await scheduler.poll();
	assert.equal(scheduler.status().scheduled, false);
	scheduler.stop();
});

test("DeployScheduler fires onRestartDue once at midnight", async () =>
{
	let now = new Date(2026, 7, 27, 23, 0, 0, 0).getTime();
	let restarts = 0;
	const scheduler = new DeployScheduler({
		repoRoot: ".",
		enabled: true,
		now: () => now,
		checkRemote: async () => ({ ok: true, ahead: true, local: "a", remote: "b" }),
		onRestartDue ()
		{ restarts += 1; }
	});
	await scheduler.poll();
	const at = scheduler.status().scheduledAt;
	now = at;
	scheduler.tick();
	scheduler.tick();
	assert.equal(restarts, 1);
	scheduler.stop();
});
