using System.Globalization; using System.Text.Json; using HomeAssistant.HistoryReplay.HomeAssistantClient; using Microsoft.Extensions.Logging; namespace HomeAssistant.HistoryReplay.HistoryData; public sealed class HomeAssistantHistoryProvider( IHomeAssistantApiClient client, ILogger logger) : IHistoryDataProvider { private const int MaxEntitiesPerRequest = 10; public async Task FetchHistoryAsync( IReadOnlyList entityIds, DateTimeOffset startTime, DateTimeOffset endTime, CancellationToken cancellationToken = default) { var timeline = new HistoryTimeline(); var batches = ChunkEntities(entityIds, MaxEntitiesPerRequest); var tasks = batches.Select(batch => FetchBatchAsync(batch, startTime, endTime, cancellationToken)); var results = await Task.WhenAll(tasks).ConfigureAwait(false); foreach (var batchTimeline in results) { foreach (var entityId in batchTimeline.GetEntityIds()) { timeline.AddEntries(entityId, batchTimeline.GetEntityHistory(entityId)); } } logger.LogInformation( "Fetched history for {EntityCount} entities: {EntryCount} total entries ({Start} to {End})", entityIds.Count, timeline.TotalEntryCount, startTime, endTime); return timeline; } private async Task FetchBatchAsync( IReadOnlyList entityIds, DateTimeOffset startTime, DateTimeOffset endTime, CancellationToken cancellationToken) { var timeline = new HistoryTimeline(); var entityIdsString = string.Join(",", entityIds); logger.LogDebug("Fetching history batch for: {Entities}", entityIdsString); try { var result = await client.GetHistoryAsync( entityIdsString, startTime, endTime, minimalResponse: false, cancellationToken) .ConfigureAwait(false); ParseHistoryResponse(result, timeline); } catch (Exception ex) { logger.LogError(ex, "Failed to fetch history for entities: {Entities}", entityIdsString); } return timeline; } private void ParseHistoryResponse(JsonElement response, HistoryTimeline timeline) { if (response.ValueKind != JsonValueKind.Array) { return; } foreach (var entityArray in response.EnumerateArray()) { if (entityArray.ValueKind != JsonValueKind.Array) { continue; } foreach (var stateObj in entityArray.EnumerateArray()) { var entry = ParseStateEntry(stateObj); if (entry is not null) { timeline.AddEntries(entry.EntityId, [entry]); } } } } private HistoryStateEntry? ParseStateEntry(JsonElement stateObj) { if (!stateObj.TryGetProperty("entity_id", out var entityIdProp)) { return null; } var entityId = entityIdProp.GetString(); if (string.IsNullOrEmpty(entityId)) { return null; } var state = stateObj.TryGetProperty("state", out var stateProp) ? stateProp.GetString() : null; DateTimeOffset lastChanged; if (stateObj.TryGetProperty("last_changed", out var lastChangedProp)) { if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out lastChanged)) { return null; } } else { return null; } Dictionary? attributes = null; if (stateObj.TryGetProperty("attributes", out var attrProp) && attrProp.ValueKind == JsonValueKind.Object) { attributes = ParseAttributes(attrProp); } return new HistoryStateEntry { EntityId = entityId, State = state, LastChanged = lastChanged, Attributes = attributes }; } private static Dictionary ParseAttributes(JsonElement attrElement) { var attributes = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var prop in attrElement.EnumerateObject()) { attributes[prop.Name] = prop.Value.ValueKind switch { JsonValueKind.String => prop.Value.GetString() ?? string.Empty, JsonValueKind.Number => prop.Value.GetDouble(), JsonValueKind.True => true, JsonValueKind.False => false, _ => prop.Value.GetRawText() }; } return attributes; } private static IReadOnlyList> ChunkEntities(IReadOnlyList entities, int chunkSize) { var chunks = new List>(); for (var i = 0; i < entities.Count; i += chunkSize) { var chunk = entities.Skip(i).Take(chunkSize).ToList(); chunks.Add(chunk); } return chunks; } }