using System.Collections.Concurrent;
using System.Text.Json;
using Heimdall.Application.DTOs;
namespace Heimdall.Agent.Services;
///
/// Holds the camera assignments the agent must capture. The Central is the
/// source of truth: cameras are shipped as flat camera.<id>.name|rtsp|sub_rtsp|enabled
/// keys through the settings pipeline (full reload + live SettingChanged).
/// A local list from AgentOptions.Cameras serves as a fallback until
/// the first Central config is received.
///
public sealed class CameraConfigStore
{
private ConcurrentDictionary _central = new();
private IReadOnlyList _localFallback = [];
private volatile bool _centralReceived;
/// Raised whenever the effective camera list may have changed.
public event EventHandler? Changed;
/// Sets the local fallback list (used until Central config arrives).
public void SetLocalFallback(IReadOnlyList cameras)
{
_localFallback = cameras;
RaiseChanged();
}
///
/// Applies a single camera.<id>.<field> setting key received from
/// the Central. Any such key marks the Central list as authoritative.
///
public void ApplyCameraSetting(string key, string value)
{
// camera..
var parts = key.Split('.', 3);
if (parts.Length != 3 || !Guid.TryParse(parts[1], out var cameraId))
return;
_centralReceived = true;
_central.AddOrUpdate(
cameraId,
_ => BuildConfig(cameraId, parts[2], value),
(_, existing) => existing with
{
DetectionProfile = parts[2] == "profile" ? ParseProfile(value) : existing.DetectionProfile,
Name = parts[2] == "name" ? value : existing.Name,
RtspUrl = parts[2] == "rtsp" ? value : existing.RtspUrl,
SubRtspUrl = parts[2] == "sub_rtsp" ? value : existing.SubRtspUrl,
Enabled = parts[2] == "enabled" ? ParseBool(value) : existing.Enabled,
});
RaiseChanged();
}
///
/// Marks the Central config as received; the local fallback is no longer
/// used, even if the Central list is empty.
///
public void MarkCentralReceived()
{
if (_centralReceived)
return;
_centralReceived = true;
RaiseChanged();
}
/// Atomically replace the authoritative snapshot, including removals.
public void ReplaceCentral(IReadOnlyDictionary settings)
{
var replacement = new CameraConfigStore();
foreach (var setting in settings.Where(s => s.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase)))
replacement.ApplyCameraSetting(setting.Key, setting.Value);
Interlocked.Exchange(ref _central, replacement._central);
_centralReceived = true;
RaiseChanged();
}
/// Effective camera assignments: Central list, or local fallback before that.
public IReadOnlyList Cameras =>
_centralReceived ? _central.Values.ToArray() : _localFallback;
private static AgentCameraConfig BuildConfig(Guid cameraId, string field, string value) => new(
cameraId,
field == "name" ? value : string.Empty,
field == "rtsp" ? value : string.Empty,
field == "sub_rtsp" ? value : null,
field == "enabled" ? ParseBool(value) : true,
field == "profile" ? ParseProfile(value) : null);
private static DetectionProfileDto ParseProfile(string value)
{
var profile = JsonSerializer.Deserialize(value) ?? throw new ArgumentException("Empty detection profile");
profile.Validate();
return profile;
}
private static bool ParseBool(string value) =>
bool.TryParse(value, out var parsed) ? parsed : value is "1" or "true" or "True";
private void RaiseChanged() => Changed?.Invoke(this, EventArgs.Empty);
}