using AutoForge.Application.Features.Vehicles.Diagnostics; using AutoForge.Application.Features.Vehicles.Profiles; using AutoForge.Application.ExecutionTargets; using AutoForge.Components; using AutoForge.Core.ExecutionTargets; using AutoForge.Core.Vehicles; using AutoForge.Diagnostics; namespace AutoForge.UI.Features.Vehicles.Diagnostics; public sealed class DiagnosticPageViewModel( IVehicleProfileService profiles, IDiagnosticSessionService sessions) : IDisposable { private CancellationTokenSource? _pending; public IReadOnlyList AvailableProfiles { get; private set; } = profiles.List(); public IReadOnlyList Providers => sessions.Providers; public string? SelectedProfileIdentifier { get; set; } public int? SelectedProfileRevision { get; set; } public string? SelectedProviderIdentifier { get; set; } public ExecutionTargetKind? SelectedTargetKind { get; set; } public DiagnosticSession? ActiveSession { get; private set; } public IReadOnlyList DiscoveredModules { get; private set; } = []; public string? DiscoverySummary { get; private set; } public IReadOnlyDictionary TroubleCodes { get; private set; } = new Dictionary(StringComparer.OrdinalIgnoreCase); public IReadOnlyDictionary Signals { get; private set; } = new Dictionary(StringComparer.OrdinalIgnoreCase); public IReadOnlyList OperationMessages { get; private set; } = []; public bool IsBusy => _pending is not null; public StatusNoticeTone StatusTone { get; private set; } = StatusNoticeTone.Information; public string StatusMessage { get; private set; } = sessions.Providers.Count == 0 ? "No diagnostic providers are available. No session is open." : "Select an exact saved profile revision and provider, then explicitly open a simulation session. Metadata selection alone does not connect."; public void LoadSyntheticExample() { try { var imported = profiles.Import(ReadSyntheticProfile()); AvailableProfiles = profiles.List(); StatusTone = StatusNoticeTone.Success; StatusMessage = $"Loaded synthetic profile '{imported.ProfileIdentifier}' revision {imported.Revision}. Select it explicitly; no session was opened."; } catch (VehicleProfileInterchangeException exception) { SetFailure(exception.Message); } catch (VehicleProfileCatalogException exception) { SetFailure(exception.Message); } } public async Task OpenSessionAsync() { if (ActiveSession is not null) { SetFailure("Close the current session before opening another explicit session."); return; } if (SelectedProfileIdentifier is null || SelectedProfileRevision is null || SelectedProviderIdentifier is null || SelectedTargetKind is null) { SetFailure("Select an exact saved profile revision, provider identifier and target kind before opening a session."); return; } var cancellation = BeginPending(); try { var session = await sessions.OpenAsync( SelectedProfileIdentifier, SelectedProfileRevision.Value, SelectedProviderIdentifier, SelectedTargetKind.Value, cancellation.Token); ActiveSession = session; ResetSessionResults(); SetInformation( $"Simulation session {session.Identity.SessionIdentifier} opened for profile '{session.Identity.ProfileIdentifier}' revision {session.Identity.ProfileRevision}. No physical connection was attempted."); } catch (DiagnosticSessionException exception) { SetFailure(exception.Message); } catch (OperationCanceledException) { SetFailure("Opening the simulation session was cancelled."); } catch (VehicleProfileCatalogException exception) { SetFailure(exception.Message); } catch (TargetSelectionException exception) { SetFailure(exception.Message); } catch (ArgumentException exception) { SetFailure(exception.Message); } finally { EndPending(cancellation); } } public async Task DiscoverAsync() { var session = ActiveSession; if (session is null) { SetFailure("Open an explicit simulation session before discovery."); return; } var cancellation = BeginPending(); try { var result = await session.DiscoverAsync(cancellation.Token); if (!IsCurrent(session)) { return; } DiscoveredModules = result.Endpoints; DiscoverySummary = $"Expected endpoints: {result.ExpectedEndpointCount}; validated positive probes: {result.ValidatedProbeCount}; profile-verified identities: {result.IdentifiedModuleCount}."; SetInformation($"Discovery completed. {DiscoverySummary}"); OperationMessages = result.Endpoints .SelectMany(endpoint => new[] { endpoint.ProbeError is null ? null : $"{endpoint.Endpoint.ModuleIdentifier} probe: {endpoint.ProbeOutcome} — {endpoint.ProbeError}", endpoint.IdentityError is null ? null : $"{endpoint.Endpoint.ModuleIdentifier} identity ({endpoint.IdentityStatus}{(endpoint.IdentityOutcome is { } outcome ? $", {outcome}" : string.Empty)}): {endpoint.IdentityError}" }) .Where(message => message is not null) .Select(message => message!) .ToArray(); if (result.Endpoints.Any(endpoint => endpoint.ProbeOutcome == DiagnosticOutcome.Cancelled || endpoint.IdentityOutcome == DiagnosticOutcome.Cancelled)) { SetFailure($"Module discovery was cancelled; completed probe evidence is retained without treating any unavailable identity as verified. {DiscoverySummary}"); } } finally { EndPending(cancellation); } } public async Task ReadModuleAsync(string moduleIdentifier) { var session = ActiveSession; var discovered = DiscoveredModules.FirstOrDefault(entry => entry.Identity is not null && StringComparer.OrdinalIgnoreCase.Equals(entry.Endpoint.ModuleIdentifier, moduleIdentifier)); if (session is null || discovered?.Identity is null) { SetFailure("Read requests require a profile-verified identity from the current session's discovery results."); return; } var cancellation = BeginPending(); try { var dtcResult = discovered.ImplementedServices.Contains(DiagnosticServices.ReadTroubleCodes, StringComparer.Ordinal) ? await session.ReadTroubleCodesAsync(discovered.Endpoint, cancellation.Token) : DiagnosticOperationResult.Failure( DiagnosticOutcome.NegativeResponse, "UNSUPPORTED_SERVICE", "This virtual endpoint does not implement DTC retrieval."); var signalResult = discovered.ImplementedServices.Contains(DiagnosticServices.ReadSignals, StringComparer.Ordinal) ? await session.ReadSignalsAsync(discovered.Endpoint, cancellation.Token) : DiagnosticOperationResult.Failure( DiagnosticOutcome.NegativeResponse, "UNSUPPORTED_SERVICE", "This virtual endpoint does not implement static signal retrieval."); if (!IsCurrent(session)) { return; } var dtcs = TroubleCodes.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase); var signals = Signals.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase); if (dtcResult.IsSuccess) { dtcs[moduleIdentifier] = dtcResult.Value!; } if (signalResult.IsSuccess) { signals[moduleIdentifier] = signalResult.Value!; } TroubleCodes = dtcs; Signals = signals; OperationMessages = new[] { FormatResult("DTC read", dtcResult.Outcome, dtcResult.Error), FormatResult("Static signal read", signalResult.Outcome, signalResult.Error) } .Where(message => message is not null) .Select(message => message!) .ToArray(); if (dtcResult.Outcome == DiagnosticOutcome.Cancelled || signalResult.Outcome == DiagnosticOutcome.Cancelled) { SetFailure($"Diagnostic reads for '{moduleIdentifier}' were cancelled; no cancelled response is presented as data."); } else if (!dtcResult.IsSuccess || !signalResult.IsSuccess) { SetFailure($"One or more diagnostic reads for '{moduleIdentifier}' failed. See the explicit operation outcomes."); } else { SetInformation($"Diagnostic reads completed for '{moduleIdentifier}'. Empty DTC results are valid only when explicitly returned by the module."); } } finally { EndPending(cancellation); } } public async Task ClearTroubleCodesAsync(string moduleIdentifier) { var session = ActiveSession; var discovered = DiscoveredModules.FirstOrDefault(entry => entry.Identity is not null && StringComparer.OrdinalIgnoreCase.Equals(entry.Endpoint.ModuleIdentifier, moduleIdentifier)); if (session is null || discovered?.Identity is null) { SetFailure("Virtual DTC clear requires a profile-verified identity from the current simulation session."); return; } if (!discovered.ImplementedServices.Contains(DiagnosticServices.ClearTroubleCodes, StringComparer.Ordinal)) { SetFailure("This virtual module does not support DTC clearing."); return; } var cancellation = BeginPending(); try { var clear = await session.ClearTroubleCodesAndVerifyAsync(discovered.Endpoint, cancellation.Token); if (!IsCurrent(session)) { return; } if (clear.Readback?.IsSuccess == true) { var dtcs = TroubleCodes.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase); dtcs[moduleIdentifier] = clear.Readback.Value!; TroubleCodes = dtcs; } if (!clear.IsVerified) { var acknowledgementMessage = clear.Acknowledgement.IsSuccess ? $"Virtual clear acknowledgement received ({clear.Acknowledgement.Value!.ClearedCount} item(s))." : $"Virtual clear acknowledgement: {clear.Acknowledgement.Outcome}."; OperationMessages = [ acknowledgementMessage, $"Verification failed or is uncertain: {clear.VerificationError} No physical write was performed." ]; SetFailure(OperationMessages[1]); return; } OperationMessages = [ $"Virtual clear acknowledgement received ({clear.Acknowledgement.Value!.ClearedCount} item(s)).", "Fresh readback verified that no DTCs remain." ]; SetInformation($"Fresh readback verified an empty virtual DTC state for '{moduleIdentifier}'. No physical write was performed."); } finally { EndPending(cancellation); } } public async Task ResetSessionAsync() { var session = ActiveSession; if (session is null) { SetFailure("There is no session to reset."); return; } var cancellation = BeginPending(); try { var reset = await sessions.ResetAsync(session, cancellation.Token); ActiveSession = reset; ResetSessionResults(); SetInformation($"Session state reset to its configured synthetic initial values. New session: {reset.Identity.SessionIdentifier}."); } catch (DiagnosticSessionException exception) { ActiveSession = null; SetFailure(exception.Message); } catch (OperationCanceledException) { ActiveSession = null; SetFailure("Session reset was cancelled after closing the previous session."); } finally { EndPending(cancellation); } } public async Task CloseSessionAsync() { var session = ActiveSession; if (session is null) { SetInformation("No diagnostic session is open."); return; } _pending?.Cancel(); ActiveSession = null; ResetSessionResults(); await session.DisposeAsync(); SetInformation($"Session {session.Identity.SessionIdentifier} closed; its isolated virtual state and trace are released."); } public void Dispose() { _pending?.Cancel(); if (ActiveSession is { } session) { ActiveSession = null; ResetSessionResults(); session.DisposeAsync().AsTask().GetAwaiter().GetResult(); } } public void CancelPending() => _pending?.Cancel(); private CancellationTokenSource BeginPending() { if (_pending is not null) { throw new InvalidOperationException("A diagnostic operation is already pending."); } _pending = new CancellationTokenSource(); StatusTone = StatusNoticeTone.Information; StatusMessage = "Diagnostic operation is pending. Cancellation remains available."; return _pending; } private void EndPending(CancellationTokenSource cancellation) { if (ReferenceEquals(_pending, cancellation)) { _pending = null; } cancellation.Dispose(); } private bool IsCurrent(DiagnosticSession session) => ReferenceEquals(ActiveSession, session) && !session.IsClosed; private void ResetSessionResults() { DiscoveredModules = []; DiscoverySummary = null; TroubleCodes = new Dictionary(StringComparer.OrdinalIgnoreCase); Signals = new Dictionary(StringComparer.OrdinalIgnoreCase); OperationMessages = []; } private void SetInformation(string message) { StatusTone = StatusNoticeTone.Information; StatusMessage = message; } private void SetFailure(string message) { StatusTone = StatusNoticeTone.Error; StatusMessage = message; } private void SetOperationFailure(string action, DiagnosticOutcome outcome, string? error) { OperationMessages = [$"{action}: {outcome} — {error ?? "No successful response was received."}"]; SetFailure(OperationMessages[0]); } private static string? FormatResult(string action, DiagnosticOutcome outcome, string? error) => outcome == DiagnosticOutcome.PositiveResponse ? null : $"{action}: {outcome} — {error}"; private static string ReadSyntheticProfile() { using var stream = typeof(DiagnosticPageViewModel).Assembly.GetManifestResourceStream( "AutoForge.UI.SyntheticExamples.synthetic-truck-baseline.json") ?? throw new InvalidOperationException("The source-controlled synthetic profile example is unavailable."); using var reader = new StreamReader(stream); return reader.ReadToEnd(); } }