"use client";

import { BUILD_ID, BUILD_ID_PARAM } from "./identity";

// Two forced reloads. If neither lands the current build, the layer between
// us and the origin is not going to yield to a third, and a reload loop is
// worse for the user than sitting on old code.
export const MAX_ATTEMPTS = 2;

/**
 * TWO budgets, deliberately separate.
 *
 * "version" counts "I am trying to reach build X". It is cleared the moment
 * version.json agrees with BUILD_ID, because arriving on X is success.
 *
 * "force" counts "I am on the right build and something is still broken" --
 * a chunk that will not load, or a chunk from another deployment. It must not
 * share the key above: those repairs run precisely when the version check is
 * passing, so one shared counter gets cleared by that passing check on every
 * reload, never reaches its limit, and turns a genuinely missing asset into
 * an endless reload loop.
 */
export type BudgetName = "version" | "force";

const STORAGE_KEY: Record<BudgetName, string> = {
    version: "version-reload-guard",
    force: "force-reload-guard",
};

type Record_ = { target: string; attempts: number };

// Three places to keep a count, because no single one is reliable:
//
//   memory  - always works, dies on reload
//   storage - survives reload, but throws or silently no-ops in Safari
//             Private Browsing, with site data blocked, and in some
//             PWA/WebView containers
//   URL     - survives reload, needs no permission, but is lost when the
//             user lands on a fresh URL (which correctly means a fresh start)
//
// Storage-only was the original design. Where storage was blocked the count
// was permanently 0, so the limit was never reached and the tab reloaded
// forever -- silently, and worst on exactly the installed-PWA clients this
// recovery exists to help. The highest of the three wins.
const memory: Partial<Record<BudgetName, Record_>> = {};

/**
 * Take one attempt from a budget.
 *
 * @returns the 1-based attempt number to use, or null when the budget for
 *          this target is spent. On null the caller must NOT reload anyway --
 *          that is the loop this prevents.
 */
export function claimAttempt(budget: BudgetName, target: string): number | null {
    const used = Math.max(
        readMemory(budget, target),
        readStorage(budget, target),
        readUrl(target)
    );

    if (used >= MAX_ATTEMPTS) return null;

    const next = used + 1;
    const record: Record_ = { target, attempts: next };

    memory[budget] = record;
    try {
        sessionStorage.setItem(STORAGE_KEY[budget], JSON.stringify(record));
    } catch { }

    return next;
}

/** Clears one budget. Never clears the others. */
export function clearBudget(budget: BudgetName): void {
    delete memory[budget];
    try {
        sessionStorage.removeItem(STORAGE_KEY[budget]);
    } catch { }
}

/**
 * The `_r` value a repair writes: "<target>.a<attempt>.<base36 time>".
 *
 * The trailing timestamp is what makes it a URL no cache has seen. The a<n>
 * segment is the storage-free attempt counter read back by readUrl(). An
 * ordinary navigation stamps a plain _r=<BUILD_ID> (see identity.ts), which
 * parses as attempt 0 -- so arriving via a normal link resets the budget,
 * which is correct: that is a fresh situation.
 */
export function buildStamp(target: string, attempt: number): string {
    return `${target}.a${attempt}.${Date.now().toString(36)}`;
}

function readMemory(budget: BudgetName, target: string): number {
    const rec = memory[budget];
    return rec && rec.target === target ? rec.attempts : 0;
}

function readStorage(budget: BudgetName, target: string): number {
    try {
        const raw = sessionStorage.getItem(STORAGE_KEY[budget]);
        if (!raw) return 0;

        const parsed = JSON.parse(raw);
        if (typeof parsed?.target !== "string" || typeof parsed?.attempts !== "number") {
            return 0;
        }

        return parsed.target === target ? parsed.attempts : 0;
    } catch {
        return 0;
    }
}

function readUrl(target: string): number {
    try {
        const raw = new URLSearchParams(window.location.search).get(BUILD_ID_PARAM);
        if (!raw) return 0;

        const parts = raw.split(".");
        // Only trust a count belonging to the target being repaired; a stamp
        // from a different build says nothing about this attempt.
        if (parts[0] !== target) return 0;

        // Start at 1: parts[0] is the build id, and a build id can itself look
        // like a counter. They are 10 hex chars, so roughly one in a thousand
        // comes out as "a" followed by nine digits -- e.g. a367613375 -- which
        // this pattern would read as attempt 367,613,375 and treat as instantly
        // over budget, silently disabling recovery for a whole release.
        for (let i = 1; i < parts.length; i++) {
            const match = /^a(\d+)$/.exec(parts[i]);
            if (match) return Number(match[1]);
        }
    } catch { }

    return 0;
}

/** Diagnostics only -- what the current URL claims about this build. */
export function attemptsInUrl(): number {
    return readUrl(BUILD_ID);
}
