// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2026 Vorion LLC
/**
 * INTENT Metrics - Prometheus-compatible observability
 *
 * Provides comprehensive metrics for monitoring intent processing,
 * queue health, trust gate decisions, and system performance.
 *
 * Note: This module now uses the shared vorionRegistry from common/metrics-registry.ts
 * to avoid circular dependencies. The intentRegistry export is maintained for backwards
 * compatibility but points to the shared registry.
 */
import { Counter, Histogram, Gauge } from 'prom-client';
// Import the shared registry and re-export for backwards compatibility
// Also re-export metrics that were moved to common/metrics-registry.ts
import { vorionRegistry, queryTimeouts, tokensRevokedTotal, tokenRevocationChecks, recordQueryTimeout, } from '../common/metrics-registry.js';
// Re-export the shared registry as intentRegistry for backwards compatibility
export const intentRegistry = vorionRegistry;
// Re-export moved metrics for backwards compatibility
export { queryTimeouts, tokensRevokedTotal, tokenRevocationChecks, recordQueryTimeout };
// ============================================================================
// Intent Lifecycle Metrics
// ============================================================================
/**
 * Total intents submitted, labeled by tenant, intent type, and outcome
 */
export const intentsSubmittedTotal = new Counter({
    name: 'vorion_intents_submitted_total',
    help: 'Total number of intents submitted',
    labelNames: ['tenant_id', 'intent_type', 'outcome'],
    registers: [intentRegistry],
});
/**
 * Intent status transitions
 */
export const intentStatusTransitions = new Counter({
    name: 'vorion_intent_status_transitions_total',
    help: 'Total number of intent status transitions',
    labelNames: ['tenant_id', 'from_status', 'to_status'],
    registers: [intentRegistry],
});
/**
 * Current intents by status (gauge)
 */
export const intentsCurrentByStatus = new Gauge({
    name: 'vorion_intents_current',
    help: 'Current number of intents by status',
    labelNames: ['tenant_id', 'status'],
    registers: [intentRegistry],
});
/**
 * Intent processing duration (from submission to terminal state)
 * Re-exported from common/metrics to avoid duplicate registration on vorionRegistry.
 */
export { intentProcessingDurationSeconds as intentProcessingDuration } from '../common/metrics.js';
// ============================================================================
// Trust Gate Metrics
// ============================================================================
/**
 * Trust gate evaluations
 */
export const trustGateEvaluations = new Counter({
    name: 'vorion_trust_gate_evaluations_total',
    help: 'Total trust gate evaluations',
    labelNames: ['tenant_id', 'intent_type', 'result'], // result: passed, rejected, bypassed
    registers: [intentRegistry],
});
/**
 * Trust level distribution at submission
 */
export const trustLevelAtSubmission = new Histogram({
    name: 'vorion_trust_level_at_submission',
    help: 'Distribution of trust levels at intent submission',
    labelNames: ['tenant_id', 'intent_type'],
    buckets: [0, 1, 2, 3, 4],
    registers: [intentRegistry],
});
// ============================================================================
// Queue Metrics
// ============================================================================
/**
 * Queue depth (waiting jobs)
 */
export const queueDepth = new Gauge({
    name: 'vorion_queue_depth',
    help: 'Number of jobs waiting in queue',
    labelNames: ['queue_name'],
    registers: [intentRegistry],
});
/**
 * Queue active jobs
 */
export const queueActiveJobs = new Gauge({
    name: 'vorion_queue_active_jobs',
    help: 'Number of jobs currently being processed',
    labelNames: ['queue_name'],
    registers: [intentRegistry],
});
/**
 * Jobs processed total
 */
export const jobsProcessedTotal = new Counter({
    name: 'vorion_jobs_processed_total',
    help: 'Total jobs processed by queue workers',
    labelNames: ['queue_name', 'result'], // result: success, failure, retry
    registers: [intentRegistry],
});
/**
 * Job processing duration
 */
export const jobProcessingDuration = new Histogram({
    name: 'vorion_job_processing_duration_seconds',
    help: 'Time to process a single job',
    labelNames: ['queue_name'],
    buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
    registers: [intentRegistry],
});
/**
 * Dead letter queue size
 */
export const dlqSize = new Gauge({
    name: 'vorion_dlq_size',
    help: 'Number of jobs in dead letter queue',
    registers: [intentRegistry],
});
// ============================================================================
// Escalation Metrics
// ============================================================================
/**
 * Escalations created
 * Uses registry lookup to avoid duplicate registration if common/metrics.ts loaded first.
 */
export const escalationsCreated = intentRegistry.getSingleMetric('vorion_escalations_created_total') ?? new Counter({
    name: 'vorion_escalations_created_total',
    help: 'Total escalations created',
    labelNames: ['tenant_id', 'intent_type', 'reason_category'],
    registers: [intentRegistry],
});
/**
 * Escalation resolutions
 */
export const escalationResolutions = new Counter({
    name: 'vorion_escalation_resolutions_total',
    help: 'Total escalation resolutions',
    labelNames: ['tenant_id', 'resolution'], // resolution: approved, rejected, timeout
    registers: [intentRegistry],
});
/**
 * Escalation pending duration
 */
export const escalationPendingDuration = new Histogram({
    name: 'vorion_escalation_pending_duration_seconds',
    help: 'Time escalations remain pending before resolution',
    labelNames: ['tenant_id', 'resolution'],
    buckets: [60, 300, 600, 1800, 3600, 7200, 14400, 28800, 86400],
    registers: [intentRegistry],
});
/**
 * Current pending escalations
 */
export const escalationsPending = new Gauge({
    name: 'vorion_escalations_pending',
    help: 'Current number of pending escalations',
    labelNames: ['tenant_id'],
    registers: [intentRegistry],
});
// ============================================================================
// Encryption Metrics
// ============================================================================
/**
 * Encryption operations
 */
export const encryptionOperations = new Counter({
    name: 'vorion_encryption_operations_total',
    help: 'Total encryption/decryption operations',
    labelNames: ['operation'], // operation: encrypt, decrypt
    registers: [intentRegistry],
});
/**
 * Encryption duration
 */
export const encryptionDuration = new Histogram({
    name: 'vorion_encryption_duration_seconds',
    help: 'Time for encryption/decryption operations',
    labelNames: ['operation'],
    buckets: [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1],
    registers: [intentRegistry],
});
// ============================================================================
// Policy Evaluation Metrics
// ============================================================================
/**
 * Policy evaluations total
 * Uses registry lookup to avoid duplicate registration if common/metrics.ts loaded first.
 */
export const policyEvaluationsTotal = intentRegistry.getSingleMetric('vorion_policy_evaluations_total') ?? new Counter({
    name: 'vorion_policy_evaluations_total',
    help: 'Total policy evaluations',
    labelNames: ['tenant_id', 'namespace', 'result'], // result: allow, deny, escalate
    registers: [intentRegistry],
});
/**
 * Policy evaluation duration
 * Uses registry lookup to avoid duplicate registration if common/metrics.ts loaded first.
 */
export const policyEvaluationDuration = intentRegistry.getSingleMetric('vorion_policy_evaluation_duration_seconds') ?? new Histogram({
    name: 'vorion_policy_evaluation_duration_seconds',
    help: 'Time to evaluate policies',
    labelNames: ['tenant_id', 'namespace'],
    buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1],
    registers: [intentRegistry],
});
/**
 * Policies matched per evaluation
 */
export const policiesMatchedPerEvaluation = new Histogram({
    name: 'vorion_policies_matched_per_evaluation',
    help: 'Number of policies that matched per evaluation',
    labelNames: ['tenant_id', 'namespace'],
    buckets: [0, 1, 2, 3, 5, 10, 20],
    registers: [intentRegistry],
});
/**
 * Policy overrides (policy action differed from rule action)
 */
export const policyOverridesTotal = new Counter({
    name: 'vorion_policy_overrides_total',
    help: 'Total times policy evaluation overrode rule decision',
    labelNames: ['tenant_id', 'rule_action', 'policy_action'],
    registers: [intentRegistry],
});
/**
 * Policies loaded from cache vs database
 */
export const policyLoadSource = new Counter({
    name: 'vorion_policy_load_source_total',
    help: 'Policy load source (local cache, redis, database)',
    labelNames: ['source'], // source: local, redis, database
    registers: [intentRegistry],
});
// ============================================================================
// Database Metrics
// ============================================================================
/**
 * Database query duration (histogram)
 */
export const dbQueryDuration = new Histogram({
    name: 'vorion_db_query_duration_seconds',
    help: 'Database query execution time in seconds',
    labelNames: ['operation'], // operation: select, insert, update, delete, other
    buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
    registers: [intentRegistry],
});
/**
 * Total database queries by operation type
 */
export const dbQueryTotal = new Counter({
    name: 'vorion_db_query_total',
    help: 'Total number of database queries by operation type',
    labelNames: ['operation'], // operation: select, insert, update, delete, other
    registers: [intentRegistry],
});
/**
 * Total failed database queries
 */
export const dbQueryErrorsTotal = new Counter({
    name: 'vorion_db_query_errors_total',
    help: 'Total number of failed database queries',
    labelNames: ['operation', 'error_type'],
    registers: [intentRegistry],
});
// Note: queryTimeouts metric moved to common/metrics-registry.ts to break circular dependency.
// Re-exported above for backwards compatibility.
/**
 * Current active database connections
 */
export const dbPoolConnectionsActive = new Gauge({
    name: 'vorion_db_pool_connections_active',
    help: 'Current number of active database connections',
    registers: [intentRegistry],
});
/**
 * Current idle database connections
 */
export const dbPoolConnectionsIdle = new Gauge({
    name: 'vorion_db_pool_connections_idle',
    help: 'Current number of idle database connections',
    registers: [intentRegistry],
});
/**
 * Clients waiting for a connection
 */
export const dbPoolConnectionsWaiting = new Gauge({
    name: 'vorion_db_pool_connections_waiting',
    help: 'Number of clients waiting for a database connection',
    registers: [intentRegistry],
});
// ============================================================================
// Lock Contention Metrics
// ============================================================================
/**
 * Lock contention events during deduplication
 */
export const deduplicateLockContentionTotal = new Counter({
    name: 'vorion_deduplicate_lock_contention_total',
    help: 'Total lock contention events during intent deduplication',
    labelNames: ['tenant_id', 'outcome'], // outcome: acquired, timeout, conflict
    registers: [intentRegistry],
});
// ============================================================================
// Trust Gate Bypass Metrics
// ============================================================================
/**
 * Trust gate bypass events (when bypassTrustGate is used)
 */
export const trustGateBypassesTotal = new Counter({
    name: 'vorion_trust_gate_bypasses_total',
    help: 'Total trust gate bypass events',
    labelNames: ['tenant_id', 'intent_type'],
    registers: [intentRegistry],
});
// ============================================================================
// Deduplication Metrics
// ============================================================================
/**
 * Intent deduplication attempts
 */
export const intentDeduplicationsTotal = new Counter({
    name: 'vorion_intent_deduplications_total',
    help: 'Total intent deduplication attempts',
    labelNames: ['tenant_id', 'outcome'], // outcome: new, duplicate, race_resolved
    registers: [intentRegistry],
});
// ============================================================================
// Policy Cache Metrics
// ============================================================================
/**
 * Policy cache hits
 */
export const policyCacheHitsTotal = new Counter({
    name: 'vorion_policy_cache_hits_total',
    help: 'Total policy cache hits',
    labelNames: ['tenant_id', 'namespace'],
    registers: [intentRegistry],
});
/**
 * Policy cache misses
 */
export const policyCacheMissesTotal = new Counter({
    name: 'vorion_policy_cache_misses_total',
    help: 'Total policy cache misses',
    labelNames: ['tenant_id', 'namespace'],
    registers: [intentRegistry],
});
// ============================================================================
// SLA Metrics
// ============================================================================
/**
 * Escalation SLA breach rate gauge (0-1 representing percentage)
 */
export const escalationSlaBreachRateGauge = new Gauge({
    name: 'vorion_escalation_sla_breach_rate',
    help: 'Current SLA breach rate for escalations (0-1)',
    labelNames: ['tenant_id'],
    registers: [intentRegistry],
});
// ============================================================================
// Intent Context Metrics
// ============================================================================
/**
 * Intent context size in bytes (histogram)
 */
export const intentContextSizeBytes = new Histogram({
    name: 'vorion_intent_context_size_bytes',
    help: 'Size of intent context payload in bytes',
    labelNames: ['tenant_id', 'intent_type'],
    buckets: [256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536],
    registers: [intentRegistry],
});
// ============================================================================
// Webhook Metrics
// ============================================================================
/**
 * Webhook delivery success counter
 */
export const webhookDeliverySuccessTotal = new Counter({
    name: 'vorion_webhook_delivery_success_total',
    help: 'Total successful webhook deliveries',
    labelNames: ['tenant_id', 'event_type'],
    registers: [intentRegistry],
});
/**
 * Webhook delivery failure counter
 */
export const webhookDeliveryFailureTotal = new Counter({
    name: 'vorion_webhook_delivery_failure_total',
    help: 'Total failed webhook deliveries',
    labelNames: ['tenant_id', 'event_type'],
    registers: [intentRegistry],
});
/**
 * Current circuit breaker state per webhook (0=closed, 1=open, 2=half_open)
 */
export const webhookCircuitBreakerState = new Gauge({
    name: 'vorion_webhook_circuit_breaker_state',
    help: 'Current circuit breaker state (0=closed, 1=open, 2=half_open)',
    labelNames: ['tenant_id', 'webhook_id'],
    registers: [intentRegistry],
});
/**
 * Total number of circuit breaker trips (circuit opening)
 */
export const webhookCircuitBreakerTripsTotal = new Counter({
    name: 'vorion_webhook_circuit_breaker_trips_total',
    help: 'Total number of times circuit breaker has tripped (opened)',
    labelNames: ['tenant_id', 'webhook_id'],
    registers: [intentRegistry],
});
/**
 * Webhook deliveries skipped due to open circuit
 */
export const webhookDeliveriesSkippedTotal = new Counter({
    name: 'vorion_webhook_deliveries_skipped_total',
    help: 'Total webhook deliveries skipped due to open circuit breaker',
    labelNames: ['tenant_id', 'webhook_id'],
    registers: [intentRegistry],
});
/**
 * Circuit breaker state transitions
 */
export const webhookCircuitBreakerTransitions = new Counter({
    name: 'vorion_webhook_circuit_breaker_transitions_total',
    help: 'Total circuit breaker state transitions',
    labelNames: ['tenant_id', 'webhook_id', 'from_state', 'to_state'],
    registers: [intentRegistry],
});
// ============================================================================
// Escalation Approval Rate Metrics
// ============================================================================
/**
 * Escalation approval rate gauge (0-1 representing percentage of approvals)
 * Uses registry lookup to avoid duplicate registration if common/metrics.ts loaded first.
 */
export const escalationApprovalRateGauge = intentRegistry.getSingleMetric('vorion_escalation_approval_rate') ?? new Gauge({
    name: 'vorion_escalation_approval_rate',
    help: 'Current approval rate for escalations (0-1)',
    labelNames: ['tenant_id'],
    registers: [intentRegistry],
});
// ============================================================================
// Circuit Breaker Metrics (Generic)
// ============================================================================
/**
 * Circuit breaker state changes (generic, for any circuit breaker)
 */
export const circuitBreakerStateChanges = new Counter({
    name: 'vorion_circuit_breaker_state_changes_total',
    help: 'Total circuit breaker state transitions',
    labelNames: ['name', 'from_state', 'to_state'],
    registers: [intentRegistry],
});
/**
 * Current circuit breaker state (gauge: 0=CLOSED, 1=HALF_OPEN, 2=OPEN)
 * Uses registry lookup to avoid duplicate registration if common/metrics.ts loaded first.
 */
export const circuitBreakerState = intentRegistry.getSingleMetric('vorion_circuit_breaker_state') ?? new Gauge({
    name: 'vorion_circuit_breaker_state',
    help: 'Current circuit breaker state (0=CLOSED, 1=HALF_OPEN, 2=OPEN)',
    labelNames: ['name'],
    registers: [intentRegistry],
});
/**
 * Circuit breaker executions
 */
export const circuitBreakerExecutions = new Counter({
    name: 'vorion_circuit_breaker_executions_total',
    help: 'Total circuit breaker executions',
    labelNames: ['name', 'result'], // result: success, failure, rejected
    registers: [intentRegistry],
});
/**
 * Circuit breaker failure count (gauge for current failure count)
 */
export const circuitBreakerFailures = new Gauge({
    name: 'vorion_circuit_breaker_failures',
    help: 'Current failure count for circuit breaker',
    labelNames: ['name'],
    registers: [intentRegistry],
});
// ============================================================================
// Per-Service Circuit Breaker Metrics
// ============================================================================
/**
 * Per-service circuit breaker state gauge (0=CLOSED, 1=HALF_OPEN, 2=OPEN)
 * Uses 'service' label for service-specific identification
 */
export const serviceCircuitBreakerState = new Gauge({
    name: 'vorion_service_circuit_breaker_state',
    help: 'Current circuit breaker state per service (0=CLOSED, 1=HALF_OPEN, 2=OPEN)',
    labelNames: ['service'],
    registers: [intentRegistry],
});
/**
 * Per-service circuit breaker failures total
 */
export const serviceCircuitBreakerFailuresTotal = new Counter({
    name: 'vorion_service_circuit_breaker_failures_total',
    help: 'Total failures recorded by circuit breaker per service',
    labelNames: ['service'],
    registers: [intentRegistry],
});
/**
 * Per-service circuit breaker successes total
 */
export const serviceCircuitBreakerSuccessesTotal = new Counter({
    name: 'vorion_service_circuit_breaker_successes_total',
    help: 'Total successful executions through circuit breaker per service',
    labelNames: ['service'],
    registers: [intentRegistry],
});
/**
 * Per-service circuit breaker trips (circuit opening)
 */
export const serviceCircuitBreakerTripsTotal = new Counter({
    name: 'vorion_service_circuit_breaker_trips_total',
    help: 'Total number of times circuit breaker has tripped (opened) per service',
    labelNames: ['service'],
    registers: [intentRegistry],
});
/**
 * Per-service circuit breaker recovery (circuit closing after half-open)
 */
export const serviceCircuitBreakerRecoveriesTotal = new Counter({
    name: 'vorion_service_circuit_breaker_recoveries_total',
    help: 'Total number of times circuit breaker has recovered (closed from half-open) per service',
    labelNames: ['service'],
    registers: [intentRegistry],
});
/**
 * Per-service circuit breaker half-open attempts
 */
export const serviceCircuitBreakerHalfOpenAttempts = new Gauge({
    name: 'vorion_service_circuit_breaker_half_open_attempts',
    help: 'Current number of half-open attempts per service',
    labelNames: ['service'],
    registers: [intentRegistry],
});
// ============================================================================
// Error Metrics
// ============================================================================
/**
 * Errors by type
 */
export const errorsTotal = new Counter({
    name: 'vorion_intent_errors_total',
    help: 'Total errors in intent processing',
    labelNames: ['error_code', 'component'],
    registers: [intentRegistry],
});
// ============================================================================
// Cleanup Metrics
// ============================================================================
/**
 * Cleanup job runs
 */
export const cleanupJobRuns = new Counter({
    name: 'vorion_cleanup_job_runs_total',
    help: 'Total cleanup job executions',
    labelNames: ['result'], // result: success, failure
    registers: [intentRegistry],
});
/**
 * Records cleaned up
 */
export const recordsCleanedUp = new Counter({
    name: 'vorion_records_cleaned_up_total',
    help: 'Total records cleaned up',
    labelNames: ['type'], // type: events, intents
    registers: [intentRegistry],
});
// ============================================================================
// Scheduler Leadership Metrics
// ============================================================================
/**
 * Leader elections total (counts each time an instance becomes leader)
 */
export const schedulerLeaderElectionsTotal = new Counter({
    name: 'vorion_scheduler_leader_elections_total',
    help: 'Total number of scheduler leadership acquisitions',
    registers: [intentRegistry],
});
/**
 * Is this instance the scheduler leader (1 if leader, 0 if not)
 */
export const schedulerIsLeader = new Gauge({
    name: 'vorion_scheduler_is_leader',
    help: 'Whether this instance is the scheduler leader (1=leader, 0=not leader)',
    registers: [intentRegistry],
});
// ============================================================================
// Token Revocation Metrics
// ============================================================================
// Note: tokensRevokedTotal and tokenRevocationChecks metrics moved to
// common/metrics-registry.ts to break circular dependency.
// Re-exported above for backwards compatibility.
// ============================================================================
// Helper Functions
// ============================================================================
/**
 * Record an intent submission with all relevant labels
 */
export function recordIntentSubmission(tenantId, intentType, outcome, trustLevel) {
    intentsSubmittedTotal.inc({
        tenant_id: tenantId,
        intent_type: intentType ?? 'default',
        outcome,
    });
    if (trustLevel !== undefined) {
        trustLevelAtSubmission.observe({ tenant_id: tenantId, intent_type: intentType ?? 'default' }, trustLevel);
    }
}
/**
 * Record a trust gate evaluation
 */
export function recordTrustGateEvaluation(tenantId, intentType, result) {
    trustGateEvaluations.inc({
        tenant_id: tenantId,
        intent_type: intentType ?? 'default',
        result,
    });
}
/**
 * Record a status transition
 */
export function recordStatusTransition(tenantId, fromStatus, toStatus) {
    intentStatusTransitions.inc({
        tenant_id: tenantId,
        from_status: fromStatus,
        to_status: toStatus,
    });
}
/**
 * Record job processing result
 */
export function recordJobResult(queueName, result, durationSeconds) {
    jobsProcessedTotal.inc({ queue_name: queueName, result });
    jobProcessingDuration.observe({ queue_name: queueName }, durationSeconds);
}
/**
 * Update queue gauges
 */
export function updateQueueGauges(queueName, waiting, active) {
    queueDepth.set({ queue_name: queueName }, waiting);
    queueActiveJobs.set({ queue_name: queueName }, active);
}
/**
 * Record an error
 */
export function recordError(errorCode, component) {
    errorsTotal.inc({ error_code: errorCode, component });
}
/**
 * Record policy evaluation metrics
 */
export function recordPolicyEvaluation(tenantId, namespace, result, durationSeconds, matchedCount) {
    policyEvaluationsTotal.inc({ tenant_id: tenantId, namespace, result });
    policyEvaluationDuration.observe({ tenant_id: tenantId, namespace }, durationSeconds);
    policiesMatchedPerEvaluation.observe({ tenant_id: tenantId, namespace }, matchedCount);
}
/**
 * Record policy override
 */
export function recordPolicyOverride(tenantId, ruleAction, policyAction) {
    policyOverridesTotal.inc({ tenant_id: tenantId, rule_action: ruleAction, policy_action: policyAction });
}
/**
 * Detect operation type from SQL query string
 */
export function detectOperationType(sql) {
    const trimmed = sql.trim().toLowerCase();
    if (trimmed.startsWith('select'))
        return 'select';
    if (trimmed.startsWith('insert'))
        return 'insert';
    if (trimmed.startsWith('update'))
        return 'update';
    if (trimmed.startsWith('delete'))
        return 'delete';
    return 'other';
}
/**
 * Record a successful database query with timing
 */
export function recordDbQuery(operation, durationSeconds) {
    dbQueryTotal.inc({ operation });
    dbQueryDuration.observe({ operation }, durationSeconds);
}
/**
 * Record a failed database query
 */
export function recordDbQueryError(operation, errorType) {
    dbQueryErrorsTotal.inc({ operation, error_type: errorType });
}
// Note: recordQueryTimeout function moved to common/metrics-registry.ts.
// Re-exported above for backwards compatibility.
/**
 * Update database pool connection gauges
 */
export function updateDbPoolMetrics(active, idle, waiting) {
    dbPoolConnectionsActive.set(active);
    dbPoolConnectionsIdle.set(idle);
    dbPoolConnectionsWaiting.set(waiting);
}
// ============================================================================
// New Observability Metrics Helper Functions
// ============================================================================
/**
 * Record lock contention during deduplication
 */
export function recordLockContention(tenantId, outcome) {
    deduplicateLockContentionTotal.inc({ tenant_id: tenantId, outcome });
}
/**
 * Record trust gate bypass
 */
export function recordTrustGateBypass(tenantId, intentType) {
    trustGateBypassesTotal.inc({
        tenant_id: tenantId,
        intent_type: intentType ?? 'default',
    });
}
/**
 * Record deduplication attempt
 */
export function recordDeduplication(tenantId, outcome) {
    intentDeduplicationsTotal.inc({ tenant_id: tenantId, outcome });
}
/**
 * Record policy cache hit
 */
export function recordPolicyCacheHit(tenantId, namespace) {
    policyCacheHitsTotal.inc({ tenant_id: tenantId, namespace });
}
/**
 * Record policy cache miss
 */
export function recordPolicyCacheMiss(tenantId, namespace) {
    policyCacheMissesTotal.inc({ tenant_id: tenantId, namespace });
}
/**
 * Update SLA breach rate gauge
 */
export function updateSlaBreachRate(tenantId, breachRate) {
    escalationSlaBreachRateGauge.set({ tenant_id: tenantId }, breachRate);
}
/**
 * Record intent context size
 */
export function recordIntentContextSize(tenantId, intentType, sizeBytes) {
    intentContextSizeBytes.observe({ tenant_id: tenantId, intent_type: intentType ?? 'default' }, sizeBytes);
}
/**
 * Record webhook delivery result
 */
export function recordWebhookDelivery(tenantId, eventType, success) {
    if (success) {
        webhookDeliverySuccessTotal.inc({ tenant_id: tenantId, event_type: eventType });
    }
    else {
        webhookDeliveryFailureTotal.inc({ tenant_id: tenantId, event_type: eventType });
    }
}
/**
 * Update escalation approval rate gauge
 */
export function updateEscalationApprovalRate(tenantId, approvalRate) {
    escalationApprovalRateGauge.set({ tenant_id: tenantId }, approvalRate);
}
const CIRCUIT_STATE_VALUES = {
    CLOSED: 0,
    HALF_OPEN: 1,
    OPEN: 2,
};
/**
 * Record circuit breaker state change
 */
export function recordCircuitBreakerStateChange(name, fromState, toState) {
    circuitBreakerStateChanges.inc({
        name,
        from_state: fromState,
        to_state: toState,
    });
    circuitBreakerState.set({ name }, CIRCUIT_STATE_VALUES[toState]);
}
/**
 * Update circuit breaker state gauge
 */
export function updateCircuitBreakerState(name, state) {
    circuitBreakerState.set({ name }, CIRCUIT_STATE_VALUES[state]);
}
/**
 * Record circuit breaker execution result
 */
export function recordCircuitBreakerExecution(name, result) {
    circuitBreakerExecutions.inc({ name, result });
}
/**
 * Update circuit breaker failure count gauge
 */
export function updateCircuitBreakerFailures(name, failureCount) {
    circuitBreakerFailures.set({ name }, failureCount);
}
// ============================================================================
// Per-Service Circuit Breaker Metrics Helper Functions
// ============================================================================
/**
 * Update per-service circuit breaker state gauge
 * This is the primary metric for monitoring circuit breaker state per service
 */
export function updateServiceCircuitBreakerState(service, state) {
    serviceCircuitBreakerState.set({ service }, CIRCUIT_STATE_VALUES[state]);
}
/**
 * Record a failure for a service's circuit breaker
 */
export function recordServiceCircuitBreakerFailure(service) {
    serviceCircuitBreakerFailuresTotal.inc({ service });
}
/**
 * Record a success for a service's circuit breaker
 */
export function recordServiceCircuitBreakerSuccess(service) {
    serviceCircuitBreakerSuccessesTotal.inc({ service });
}
/**
 * Record a circuit breaker trip (circuit opening) for a service
 */
export function recordServiceCircuitBreakerTrip(service) {
    serviceCircuitBreakerTripsTotal.inc({ service });
}
/**
 * Record a circuit breaker recovery (circuit closing from half-open) for a service
 */
export function recordServiceCircuitBreakerRecovery(service) {
    serviceCircuitBreakerRecoveriesTotal.inc({ service });
}
/**
 * Update the current half-open attempts gauge for a service
 */
export function updateServiceCircuitBreakerHalfOpenAttempts(service, attempts) {
    serviceCircuitBreakerHalfOpenAttempts.set({ service }, attempts);
}
/**
 * Record a complete circuit breaker state change for a service
 * This is a convenience function that updates multiple metrics at once
 */
export function recordServiceCircuitBreakerStateChange(service, fromState, toState) {
    // Update the state gauge
    updateServiceCircuitBreakerState(service, toState);
    // Also update the generic circuit breaker metrics for backward compatibility
    circuitBreakerStateChanges.inc({
        name: service,
        from_state: fromState,
        to_state: toState,
    });
    circuitBreakerState.set({ name: service }, CIRCUIT_STATE_VALUES[toState]);
    // Record specific events
    if (toState === 'OPEN') {
        recordServiceCircuitBreakerTrip(service);
    }
    else if (fromState === 'HALF_OPEN' && toState === 'CLOSED') {
        recordServiceCircuitBreakerRecovery(service);
    }
}
/**
 * Get all metrics as Prometheus text format
 */
export async function getMetrics() {
    return intentRegistry.metrics();
}
/**
 * Get metrics content type
 */
export function getMetricsContentType() {
    return intentRegistry.contentType;
}
//# sourceMappingURL=metrics.js.map