<?php

declare(strict_types=1);

namespace Atdt\Dos;

use Atdt\Db;

/**
 * The dosfs diagnostics ring (SPEC-DOSDOORS §13): the last 50
 * operations for a door with timings, kept only while the door's
 * debug toggle is on. This is how latency gets tuned: a door that
 * feels slow shows exactly which files round-trip instead of riding
 * the browser cache, and the fix is a manifest static glob.
 */
final class Diag
{
    /** @var array<string, bool> per-request debug flag cache */
    private static array $debug = [];

    public static function note(Db $db, string $slug, string $op, int $ms): void
    {
        if (!(self::$debug[$slug] ??= (bool)$db->val('SELECT debug FROM dos_doors WHERE slug = ?', [$slug]))) {
            return;
        }
        $f = Doors::stateDir($slug) . '.diag';
        $ring = json_decode((string)@file_get_contents($f), true) ?: [];
        $ring[] = ['at' => gmdate('H:i:s'), 'op' => $op, 'ms' => $ms];
        @file_put_contents($f, json_encode(array_slice($ring, -50)));
    }

    /** @return list<array{at: string, op: string, ms: int}> */
    public static function ring(string $slug): array
    {
        return json_decode((string)@file_get_contents(Doors::stateDir($slug) . '.diag'), true) ?: [];
    }

    public static function clear(string $slug): void
    {
        @unlink(Doors::stateDir($slug) . '.diag');
    }
}
