<?php

declare(strict_types=1);

require_once __DIR__.'/functions.inc.php';

const MIN_AGE_SECONDS = 45 * 60;
const MAX_AGE_SECONDS = (3 * 60 * 60) + (45 * 60);

function loadLastValidRecord(string $filename): ?array
{
	if (!is_file($filename)) {
		return null;
	}

	$lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
	if ($lines === false) {
		return null;
	}

	// Walk backwards so a partially written or invalid last line does not break the check.
	for ($i = count($lines) - 1; $i >= 0; $i--) {
		$record = json_decode($lines[$i], true);
		if (is_array($record) && json_last_error() === JSON_ERROR_NONE) {
			return $record;
		}
	}

	return null;
}

function parseRecordTime(array $record): ?DateTimeImmutable
{
	if (!isset($record['timestamp']) || !is_string($record['timestamp'])) {
		return null;
	}

	try {
		return new DateTimeImmutable($record['timestamp']);
	} catch (Throwable $e) {
		error_log('Invalid data timestamp: ' . $e->getMessage());
		return null;
	}
}

function formatLevels(array $record): string
{
	$values = [];
	foreach (['level1', 'level2', 'level3', 'level4'] as $name) {
		$values[] = $name . '=' . (isset($record[$name]) ? (int) $record[$name] : 0);
	}

	return implode(', ', $values);
}

$record = loadLastValidRecord(DATA_JSONL_FILEPATH);
if ($record === null) {
	exit(0);
}

$recordTime = parseRecordTime($record);
if ($recordTime === null) {
	exit(0);
}

$ageSeconds = time() - $recordTime->getTimestamp();
if ($ageSeconds <= MIN_AGE_SECONDS || $ageSeconds >= MAX_AGE_SECONDS) {
	exit(0);
}

$message = sprintf(
	'Nebola zaznamenaná nová hodnota hladiny kondenzu, posledná získaná hodnota je z %s (%s). Toto upozornenie príde len 3x, potom sa už nekontroluje.',
	$recordTime->format('Y-m-d H:i:s'),
	formatLevels($record)
);

notifyUsers($message);
