/ src / hooks / useDiagnostics.tsx
useDiagnostics.tsx
 1  // Copyright (c) 2026 VPL Solutions. All rights reserved.
 2  // Licensed under the MIT License. See LICENSE for details.
 3  
 4  import { useCallback, useState, type ReactNode } from 'react';
 5  import {
 6    DiagnosticsContext,
 7    initial,
 8    PRICING,
 9    type CallRecord,
10    type DiagnosticsState,
11  } from './DiagnosticsContext';
12  
13  export { type CallRecord } from './DiagnosticsContext';
14  
15  export function DiagnosticsProvider({ children }: { children: ReactNode }) {
16    const [state, setState] = useState<DiagnosticsState>(initial);
17  
18    const recordCall = useCallback(
19      (input: Omit<CallRecord, 'timestamp' | 'estimatedCost'> & { estimatedCost?: number }) => {
20        const cost = input.estimatedCost ?? PRICING[input.service] ?? 0;
21        const record: CallRecord = { ...input, timestamp: Date.now(), estimatedCost: cost };
22  
23        setState((prev) => {
24          const svc = prev.callsByService[record.service] ?? { count: 0, cost: 0 };
25          return {
26            lastCall: record,
27            calls: [...prev.calls, record],
28            totalCalls: prev.totalCalls + 1,
29            totalCost: prev.totalCost + record.estimatedCost,
30            callsByService: {
31              ...prev.callsByService,
32              [record.service]: {
33                count: svc.count + 1,
34                cost: svc.cost + record.estimatedCost,
35              },
36            },
37          };
38        });
39      },
40      [],
41    );
42  
43    const reset = useCallback(() => setState(initial), []);
44  
45    return (
46      <DiagnosticsContext.Provider value={{ ...state, recordCall, reset }}>
47        {children}
48      </DiagnosticsContext.Provider>
49    );
50  }