import {
	RESTART_WARN_BEFORE_MS,
	DEFAULT_DEPLOY_CHECK_MS,
	nextLocalMidnightMs
} from "../../../shared/deploy/schedule.js";
import { checkGitRemoteAhead } from "./gitRemote.js";

/**
 * Schedules a graceful midnight restart only when origin/<branch> is ahead of HEAD.
 * Clients see a permanent countdown toast for the whole time a restart is scheduled.
 */
export class DeployScheduler
{
	/**
	 * @param {{
	 *   repoRoot: string,
	 *   branch?: string,
	 *   checkIntervalMs?: number,
	 *   warnBeforeMs?: number,
	 *   enabled?: boolean,
	 *   now?: () => number,
	 *   checkRemote?: (repoRoot: string, branch: string) => Promise<object>,
	 *   onStatusChange?: (status: object) => void,
	 *   onRestartDue?: (status: object) => void
	 * }} options
	 */
	constructor (options)
	{
		this.repoRoot = options.repoRoot;
		this.branch = options.branch
			?? process.env.QUESTWARD_GIT_BRANCH
			?? process.env.TILE_MMO_GIT_BRANCH
			?? "master";
		this.checkIntervalMs = Math.max(
			30_000,
			Number(
				options.checkIntervalMs
				?? process.env.QUESTWARD_DEPLOY_CHECK_MS
				?? process.env.TILE_MMO_DEPLOY_CHECK_MS
			) || DEFAULT_DEPLOY_CHECK_MS
		);
		this.warnBeforeMs = options.warnBeforeMs ?? RESTART_WARN_BEFORE_MS;
		this.enabled = options.enabled
			?? (process.env.QUESTWARD_DEPLOY_SCHEDULER ?? process.env.TILE_MMO_DEPLOY_SCHEDULER) !== "0";
		this.now = options.now ?? (() => Date.now());
		this.checkRemote = options.checkRemote ?? checkGitRemoteAhead;
		this.onStatusChange = options.onStatusChange ?? (() => {});
		this.onRestartDue = options.onRestartDue ?? (() => {});

		this.scheduledAt = null;
		this.reasons = [];
		this.localCommit = null;
		this.remoteCommit = null;
		this.warningActive = false;
		this.restartFired = false;
		this.#checkTimer = null;
		this.#tickTimer = null;
		this.#checking = false;
	}

	#checkTimer;
	#tickTimer;
	#checking;

	start ()
	{
		if (!this.enabled)
		{ return; }
		void this.poll();
		this.#checkTimer = setInterval(() => { void this.poll(); }, Math.max(30_000, this.checkIntervalMs));
		this.#tickTimer = setInterval(() => this.tick(), 1000);
	}

	stop ()
	{
		if (this.#checkTimer)
		{ clearInterval(this.#checkTimer); }
		if (this.#tickTimer)
		{ clearInterval(this.#tickTimer); }
		this.#checkTimer = null;
		this.#tickTimer = null;
	}

	status ()
	{
		const now = this.now();
		const scheduled = this.scheduledAt != null;
		const warning = scheduled && now < this.scheduledAt;
		return {
			scheduled,
			scheduledAt: this.scheduledAt,
			warning: !!warning,
			reasons: [...this.reasons],
			localCommit: this.localCommit,
			remoteCommit: this.remoteCommit,
			branch: this.branch,
			remainingMs: scheduled ? Math.max(0, this.scheduledAt - now) : null
		};
	}

	async poll ()
	{
		if (!this.enabled || this.#checking || this.restartFired)
		{ return; }
		this.#checking = true;
		try
		{
			const result = await this.checkRemote(this.repoRoot, this.branch);
			if (!result?.ok)
			{ return; }
			this.localCommit = result.local ?? this.localCommit;
			this.remoteCommit = result.remote ?? this.remoteCommit;
			if (result.ahead)
			{ this.#scheduleCodeUpdate(); }
			else if (this.scheduledAt != null && this.reasons.includes("code-update"))
			{ this.#clearSchedule(); }
		}
		finally
		{
			this.#checking = false;
		}
	}

	tick ()
	{
		if (!this.enabled || this.restartFired || this.scheduledAt == null)
		{ return; }
		const now = this.now();
		if (now >= this.scheduledAt)
		{
			this.restartFired = true;
			this.warningActive = true;
			this.onRestartDue(this.status());
		}
	}

	/** Test helper: force a pending midnight restart. */
	forceScheduleForTests (scheduledAt, reasons = ["code-update"])
	{
		this.scheduledAt = scheduledAt;
		this.reasons = [...reasons];
		this.warningActive = scheduledAt != null && this.now() < scheduledAt;
		this.onStatusChange(this.status());
	}

	#scheduleCodeUpdate ()
	{
		if (this.scheduledAt != null)
		{ return; }
		this.scheduledAt = nextLocalMidnightMs(this.now());
		this.reasons = ["code-update"];
		this.warningActive = this.now() < this.scheduledAt;
		console.log(
			`[deploy] origin/${this.branch} is ahead; restart scheduled for ${new Date(this.scheduledAt).toString()}`
		);
		this.onStatusChange(this.status());
	}

	#clearSchedule ()
	{
		this.scheduledAt = null;
		this.reasons = [];
		this.warningActive = false;
		console.log("[deploy] Remote no longer ahead; cancelled scheduled restart.");
		this.onStatusChange(this.status());
	}
}
