/**
 * System State Intelligence Model
 * Phase 5: UI-Driven Architecture Lock-In
 *
 * This is the authoritative system intelligence model.
 * The UI reads from this, never computes values itself.
 *
 * Architecture:
 * Runtime State (AppState) → System Intelligence (SystemState) → UI Rendering
 *
 * The 5 mandatory intelligence surfaces are:
 * 1. system_posture
 * 2. network_context
 * 3. asset_registry_summary
 * 4. operation_feed
 * 5. capability_flags
 */
/**
 * System State Provider
 * Computes SystemState from AppState
 * This is the single source of truth for intelligence data
 */
export class SystemStateProvider {
    cachedState = null;
    lastAppStateVersion = 0;
    appStateVersion = 0;
    /**
     * Compute system posture from app state
     * Phase 5: Centralized, deterministic computation
     */
    computeSystemPosture(state) {
        // Determine overall posture
        let overallPosture;
        let sourceOfTruth;
        if (!state.systemReady) {
            overallPosture = 'CRITICAL';
            sourceOfTruth = 'system_initialization';
        }
        else if (state.gatewayConnected && state.localMode) {
            overallPosture = 'OPERATIONAL';
            sourceOfTruth = 'hybrid_mode';
        }
        else if (state.gatewayConnected) {
            overallPosture = 'OPERATIONAL';
            sourceOfTruth = 'gateway_connection';
        }
        else if (state.localMode) {
            overallPosture = 'OPERATIONAL';
            sourceOfTruth = 'local_mode';
        }
        else {
            overallPosture = 'DEGRADED';
            sourceOfTruth = 'no_connection';
        }
        // Determine execution mode
        let executionMode;
        if (state.localMode && state.gatewayConnected) {
            executionMode = 'HYBRID';
        }
        else if (state.localMode) {
            executionMode = 'LOCAL';
        }
        else if (state.gatewayConnected) {
            executionMode = 'REMOTE';
        }
        else {
            executionMode = 'LOCAL'; // Fallback
        }
        // Determine risk level
        let riskLevel;
        if (overallPosture === 'CRITICAL') {
            riskLevel = 'HIGH';
        }
        else if (overallPosture === 'DEGRADED') {
            riskLevel = 'ELEVATED';
        }
        else {
            riskLevel = 'LOW';
        }
        // Track last state change (would be tracked in state transitions)
        // For v1, use current timestamp (would track actual state transitions)
        const lastStateChange = Date.now();
        return {
            overallPosture,
            executionMode,
            riskLevel,
            lastStateChange,
        };
    }
    /**
     * Compute network context from app state
     * Phase 5: Spatial and infrastructural awareness
     */
    computeNetworkContext(state) {
        // Operator origin (privacy-safe, approximate)
        const operatorOrigin = {
            region: process.env.OPERATOR_REGION || 'UNKNOWN',
            networkType: (() => {
                if (state.localMode)
                    return 'LOCAL';
                if (state.gatewayUrl?.includes('localhost') || state.gatewayUrl?.includes('127.0.0.1')) {
                    return 'LOCAL';
                }
                if (state.gatewayUrl?.includes('vpn') || state.gatewayUrl?.includes('tunnel')) {
                    return 'VPN';
                }
                if (state.gatewayUrl) {
                    return 'CLOUD';
                }
                return 'UNKNOWN';
            })(),
        };
        // Target infrastructure
        const targetInfrastructure = {
            gatewayRegion: state.gatewayUrl
                ? this.extractRegionFromUrl(state.gatewayUrl)
                : 'NONE',
            databaseRegion: state.gatewayConnected
                ? this.extractRegionFromUrl(state.gatewayUrl || '')
                : 'NONE',
            latencyClass: (() => {
                // Simplified - would measure actual latency
                if (state.localMode)
                    return 'LOW';
                if (state.gatewayConnected)
                    return 'MEDIUM';
                return 'HIGH';
            })(),
        };
        return {
            operatorOrigin,
            targetInfrastructure,
        };
    }
    /**
     * Extract region from URL (simplified)
     */
    extractRegionFromUrl(url) {
        if (url.includes('localhost') || url.includes('127.0.0.1'))
            return 'LOCAL';
        if (url.includes('us-'))
            return 'US';
        if (url.includes('eu-'))
            return 'EU';
        if (url.includes('ap-'))
            return 'APAC';
        return 'UNKNOWN';
    }
    /**
     * Compute asset registry summary
     * Phase 5: Deployed intelligence surface
     */
    computeAssetRegistrySummary(state) {
        const total = state.customAgents.size;
        // Count by status
        const activeRuns = state.runHistory.filter(r => r.status === 'RUNNING');
        const failedRuns = state.runHistory.filter(r => r.status === 'FAILED');
        const active = activeRuns.length;
        const error = failedRuns.length > 0 && failedRuns[0].timestamp > Date.now() - 60000 ? 1 : 0;
        const idle = Math.max(0, total - active - error);
        // Primary asset (last used or pinned)
        let highlighted = null;
        if (activeRuns.length > 0) {
            const activeRun = activeRuns[activeRuns.length - 1];
            const asset = Array.from(state.customAgents.values()).find(a => a.name === activeRun.agentName);
            if (asset) {
                highlighted = {
                    name: asset.name,
                    status: 'ACTIVE',
                    reason: 'Currently executing',
                };
            }
        }
        else if (state.runHistory.length > 0) {
            const lastRun = state.runHistory[state.runHistory.length - 1];
            const asset = Array.from(state.customAgents.values()).find(a => a.name === lastRun.agentName);
            if (asset) {
                highlighted = {
                    name: asset.name,
                    status: lastRun.status === 'FAILED' ? 'ERROR' : 'IDLE',
                    reason: lastRun.status === 'FAILED' ? 'Recent failure' : 'Last used',
                };
            }
        }
        else if (total > 0) {
            const firstAsset = Array.from(state.customAgents.values())[0];
            highlighted = {
                name: firstAsset.name,
                status: 'IDLE',
                reason: 'Available',
            };
        }
        return {
            total,
            active,
            idle,
            error,
            highlighted,
        };
    }
    /**
     * Get operation feed
     * Phase 5: Living operational pulse
     */
    getOperationFeed(state) {
        // Return last 10 events (hard limit)
        return state.operationEvents.slice(-10);
    }
    /**
     * Compute capability flags
     * Phase 5: What the system is capable of right now
     */
    computeCapabilityFlags(state) {
        return {
            gateway: state.gatewayConnected ? 'READY' : 'DEGRADED',
            database: state.gatewayConnected ? 'READY' : 'NOT_INITIALIZED',
            memoryLayer: state.gatewayConnected ? 'PERSISTENT' : 'IN_MEMORY',
            security: state.currentUser ? 'JWT' : 'OPEN',
            rateLimiting: 'DISABLED', // Would check actual config
        };
    }
    /**
     * Compute complete SystemState from AppState
     * This is the single computation point
     */
    compute(state) {
        // Increment version for cache invalidation
        this.appStateVersion++;
        const systemState = {
            systemPosture: this.computeSystemPosture(state),
            networkContext: this.computeNetworkContext(state),
            assetRegistrySummary: this.computeAssetRegistrySummary(state),
            operationFeed: this.getOperationFeed(state),
            capabilityFlags: this.computeCapabilityFlags(state),
            computedAt: Date.now(),
            version: this.appStateVersion,
        };
        // Cache the result
        this.cachedState = systemState;
        this.lastAppStateVersion = this.appStateVersion;
        return systemState;
    }
    /**
     * Get cached state if available and valid
     * Otherwise compute fresh
     */
    get(state, forceRefresh = false) {
        if (!forceRefresh && this.cachedState && this.appStateVersion === this.lastAppStateVersion) {
            return this.cachedState;
        }
        return this.compute(state);
    }
    /**
     * Invalidate cache (call when state changes)
     */
    invalidate() {
        this.cachedState = null;
        this.lastAppStateVersion = 0;
    }
}
/**
 * Global system state provider instance
 * Single source of truth for intelligence data
 */
export const systemStateProvider = new SystemStateProvider();
/**
 * Get current system state
 * This is what the UI reads from
 */
export function getSystemState(state, forceRefresh = false) {
    return systemStateProvider.get(state, forceRefresh);
}
//# sourceMappingURL=system-state.js.map