using AutoForge.Application.Features.Vehicles.Profiles; using AutoForge.Application.Features.Vehicles.Simulation; using AutoForge.Core.Calibration; using AutoForge.Core.Simulation; using AutoForge.Core.Vehicles; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; namespace AutoForge.Application.Features.Vehicles.Calibration; public enum CalibrationVersionKind { Baseline, Proposed } public sealed record CalibrationModuleMetadata( string ModuleIdentifier, string? HardwareIdentifier, string? SoftwareIdentifier, string? FirmwareIdentifier, string? CalibrationIdentifier); public sealed class CalibrationVersion { internal CalibrationVersion(string workspaceIdentifier, CalibrationApplicability source, int revision, string? parent, CalibrationVersionKind kind, CalibrationValues values) { Identifier = Guid.NewGuid().ToString("N"); WorkspaceIdentifier = workspaceIdentifier; Source = source with { }; Revision = revision; ParentIdentifier = parent; Kind = kind; Values = new(values.Scalars, values.Tables); } public string Identifier { get; } public string WorkspaceIdentifier { get; } public CalibrationApplicability Source { get; } public int Revision { get; } public string? ParentIdentifier { get; } public CalibrationVersionKind Kind { get; } public CalibrationValues Values { get; } public string Label => Kind == CalibrationVersionKind.Baseline ? "Synthetic configuration-derived baseline" : "Proposed synthetic authoring revision"; } public sealed class CalibrationWorkspace { internal CalibrationWorkspace(string identifier, SyntheticEngineCalibration definition, CalibrationModuleMetadata module, IEnumerable history) { Identifier = identifier; Definition = definition; Module = module with { }; History = Array.AsReadOnly(history.ToArray()); } public string Identifier { get; } public SyntheticEngineCalibration Definition { get; } public CalibrationModuleMetadata Module { get; } public IReadOnlyList History { get; } public CalibrationVersion Head => History[^1]; public CalibrationVersion Baseline => History[0]; } public sealed record CalibrationSaveRequest( string WorkspaceIdentifier, string ExpectedHeadIdentifier, CalibrationApplicability Source, CalibrationValues Values); public sealed record CalibrationDiffEntry( string LogicalIdentifier, double? AxisCoordinate, string? AxisUnit, string Unit, double Before, double After, double Delta); public sealed record CalibrationDiff( string WorkspaceIdentifier, CalibrationApplicability Source, string FromIdentifier, string ToIdentifier, IReadOnlyList Entries); public sealed class CalibrationAuthoringService(IDynamicsConfigurationService configurations, IVehicleProfileService profiles) { public const int MaximumRevisions = 32; private readonly object _gate = new(); private CalibrationWorkspace? _workspace; public event Action? Changed; public CalibrationWorkspace? Snapshot { get { lock (_gate) return _workspace; } } public CalibrationWorkspace CreateBaseline(string configurationIdentifier) { CalibrationWorkspace workspace; lock (_gate) { if (_workspace is not null) throw Failure(CalibrationFailure.WorkspaceExists, "An authoring workspace already exists. Explicitly confirm replacement before discarding its in-memory history/draft."); workspace = BuildBaseline(configurationIdentifier); _workspace = workspace; } Changed?.Invoke(); return workspace; } public CalibrationWorkspace ReplaceBaseline(string configurationIdentifier, string expectedWorkspaceIdentifier, string expectedHeadIdentifier, bool confirmDiscard) { CalibrationWorkspace workspace; lock (_gate) { var current = RequireWorkspace(expectedWorkspaceIdentifier); if (!confirmDiscard) throw Failure(CalibrationFailure.ReplacementNotConfirmed, "Explicitly confirm that replacement discards the old in-memory history and draft."); EnsureHead(current, expectedHeadIdentifier); workspace = BuildBaseline(configurationIdentifier); _workspace = workspace; } Changed?.Invoke(); return workspace; } public CalibrationVersion Save(CalibrationSaveRequest request) { CalibrationVersion version; lock (_gate) { if (request is null) throw Failure(CalibrationFailure.InvalidCommand, "An explicit source/head/candidate request is required."); var current = RequireWorkspace(request.WorkspaceIdentifier); if (!current.Definition.Applicability.Matches(request.Source)) throw Failure(CalibrationFailure.SourceMismatch, "The expected authoring source/configuration/profile/module/model/definition does not match this workspace."); EnsureHead(current, request.ExpectedHeadIdentifier); current.Definition.Validate(request.Values); if (current.Head.Values.ContentEquals(request.Values)) return current.Head; if (current.History.Count >= MaximumRevisions) throw Failure(CalibrationFailure.HistoryLimit, "Authoring supports at most 32 saved revisions including baseline. Changed revision 33 was rejected; identical head saves remain no-ops."); version = new(current.Identifier, current.Definition.Applicability, current.Head.Revision + 1, current.Head.Identifier, CalibrationVersionKind.Proposed, request.Values); _workspace = new(current.Identifier, current.Definition, current.Module, [.. current.History, version]); } Changed?.Invoke(); return version; } internal T AtCurrentHead(string workspaceIdentifier, string headIdentifier, Func dispatch) { lock (_gate) { EnsureHead(RequireWorkspace(workspaceIdentifier), headIdentifier); return dispatch(); } } public CalibrationDiff Compare(string workspaceIdentifier, string fromIdentifier, string toIdentifier) { lock (_gate) { var current = RequireWorkspace(workspaceIdentifier); var from = FindVersion(current, fromIdentifier); var to = FindVersion(current, toIdentifier); return new(current.Identifier, current.Definition.Applicability with { }, from.Identifier, to.Identifier, CalibrationValueDifferences.Compare(from.Values, to.Values)); } } private CalibrationWorkspace BuildBaseline(string identifier) { DynamicsConfiguration configuration; VehicleProfile profile; try { configuration = configurations.Select(identifier); profile = profiles.Select(configuration.ProfileIdentifier, configuration.ProfileRevision); configuration.ValidateAgainst(profile); } catch (Exception exception) when (exception is DynamicsConfigurationException or VehicleProfileCatalogException or ArgumentException) { throw new CalibrationAuthoringException(CalibrationFailure.SourceNotFound, $"The exact configuration/profile source could not be resolved: {exception.Message}", exception); } var module = profile.Modules.SingleOrDefault(item => StringComparer.OrdinalIgnoreCase.Equals(item.InstanceIdentifier, configuration.EngineModuleIdentifier)) ?? throw Failure(CalibrationFailure.SourceNotFound, "The configuration's explicit engine module does not exist in its exact profile revision."); var applicability = new CalibrationApplicability(configuration.ProfileIdentifier, configuration.ProfileRevision, configuration.ConfigurationIdentifier, configuration.EngineModuleIdentifier, configuration.ModelIdentifier, configuration.ModelVersion, SyntheticEngineCalibration.DefinitionIdentifier, 1); var definition = new SyntheticEngineCalibration(applicability, new(SyntheticEngineCalibration.ScalarIdentifier, "rpm", configuration.Model.IdleSpeedRpm, configuration.Model.MaximumEngineSpeedRpm), new(SyntheticEngineCalibration.TableIdentifier, "rpm", "N*m", configuration.Model.EngineTorqueCurve.Select(point => point.EngineSpeedRpm), 1, 1000)); var values = new CalibrationValues([new(SyntheticEngineCalibration.ScalarIdentifier, "rpm", configuration.Model.WarmIdleTargetRpm)], [new(SyntheticEngineCalibration.TableIdentifier, "N*m", "rpm", definition.Table.Axis, configuration.Model.EngineTorqueCurve.Select(point => point.TorqueNewtonMeters))]); try { definition.Validate(values); } catch (CalibrationAuthoringException exception) { throw new CalibrationAuthoringException(CalibrationFailure.InvalidDefinition, $"This valid dynamics source is outside the bounded synthetic authoring template: {exception.Message}", exception); } var metadata = new CalibrationModuleMetadata(module.InstanceIdentifier, module.HardwareIdentifier, module.SoftwareIdentifier, module.FirmwareIdentifier, module.CalibrationIdentifier); var workspaceIdentifier = Guid.NewGuid().ToString("N"); return new(workspaceIdentifier, definition, metadata, [new(workspaceIdentifier, applicability, 1, null, CalibrationVersionKind.Baseline, values)]); } private CalibrationWorkspace RequireWorkspace(string identifier) { if (_workspace is null) throw Failure(CalibrationFailure.NoWorkspace, "Explicitly create a synthetic authoring baseline first."); if (!StringComparer.Ordinal.Equals(_workspace.Identifier, identifier)) throw Failure(CalibrationFailure.SourceMismatch, "The expected workspace/source was replaced or does not match; no cross-source authoring is allowed."); return _workspace; } private static void EnsureHead(CalibrationWorkspace current, string identifier) { if (!StringComparer.Ordinal.Equals(current.Head.Identifier, identifier)) throw Failure(CalibrationFailure.StaleHead, "The expected head is stale. Cancel/reload the latest draft explicitly before saving; no merge or lost update is allowed."); } private static CalibrationVersion FindVersion(CalibrationWorkspace current, string identifier) => current.History.SingleOrDefault(version => StringComparer.Ordinal.Equals(version.Identifier, identifier)) ?? throw Failure(CalibrationFailure.VersionNotFound, "The explicitly selected revision does not belong to this workspace/source/definition."); private static CalibrationAuthoringException Failure(CalibrationFailure failure, string message) => new(failure, message); } internal static class CalibrationValueDifferences { public static IReadOnlyList Compare(CalibrationValues before, CalibrationValues after) { var entries = new List(); var beforeScalar = before.Scalars[0]; var afterScalar = after.Scalars[0]; if (beforeScalar.Value != afterScalar.Value) entries.Add(new(beforeScalar.LogicalIdentifier, null, null, beforeScalar.Unit, beforeScalar.Value, afterScalar.Value, afterScalar.Value - beforeScalar.Value)); var beforeTable = before.Tables[0]; var afterTable = after.Tables[0]; for (var index = 0; index < beforeTable.Cells.Count; index++) { if (beforeTable.Cells[index] != afterTable.Cells[index]) entries.Add(new(beforeTable.LogicalIdentifier, beforeTable.Axis[index], beforeTable.AxisUnit, beforeTable.Unit, beforeTable.Cells[index], afterTable.Cells[index], afterTable.Cells[index] - beforeTable.Cells[index])); } return Array.AsReadOnly(entries.OrderBy(entry => entry.LogicalIdentifier, StringComparer.Ordinal) .ThenBy(entry => entry.AxisCoordinate).ToArray()); } } public static class CalibrationAuthoringServiceCollectionExtensions { public static IServiceCollection AddAutoForgeCalibrationAuthoring(this IServiceCollection services) { services.TryAddSingleton(); return services; } }