/**
 * Interface for throughput sample data
 */
export interface IThroughputSample {
  timestamp: number;
  bytesIn: number;
  bytesOut: number;
  tags?: {
    route?: string;
    ip?: string;
    [key: string]: string | undefined;
  };
}

/**
 * Interface for throughput data
 */
export interface IThroughputData {
  in: number;
  out: number;
}

/**
 * Interface for time-series throughput data
 */
export interface IThroughputHistoryPoint {
  timestamp: number;
  in: number;
  out: number;
}

export interface IRequestRateMetrics {
  perSecond: number;
  lastMinute: number;
}

/**
 * Main metrics interface with clean, grouped API
 */
/**
 * Protocol distribution for frontend (client→proxy) or backend (proxy→upstream).
 * Tracks active and total counts for h1/h2/h3/ws/other.
 */
export interface IProtocolDistribution {
  h1Active: number;
  h1Total: number;
  h2Active: number;
  h2Total: number;
  h3Active: number;
  h3Total: number;
  wsActive: number;
  wsTotal: number;
  otherActive: number;
  otherTotal: number;
}

export interface IMetrics {
  // Connection metrics
  connections: {
    active(): number;
    total(): number;
    byRoute(): Map<string, number>;
    byIP(): Map<string, number>;
    topIPs(limit?: number): Array<{ ip: string; count: number }>;
    /** Per-IP domain request counts: IP -> { domain -> count }. */
    domainRequestsByIP(): Map<string, Map<string, number>>;
    /** Top IP-domain pairs sorted by request count descending. */
    topDomainRequests(limit?: number): Array<{ ip: string; domain: string; count: number }>;
    frontendProtocols(): IProtocolDistribution;
    backendProtocols(): IProtocolDistribution;
  };
  
  // Throughput metrics (bytes per second)
  throughput: {
    instant(): IThroughputData;      // Last 1 second
    recent(): IThroughputData;       // Last 10 seconds  
    average(): IThroughputData;      // Last 60 seconds
    custom(seconds: number): IThroughputData;
    history(seconds: number): Array<IThroughputHistoryPoint>;
    byRoute(windowSeconds?: number): Map<string, IThroughputData>;  // Default: 1 second
    byIP(windowSeconds?: number): Map<string, IThroughputData>;     // Default: 1 second
  };
  
  // Request metrics
  requests: {
    perSecond(): number;
    perMinute(): number;
    total(): number;
    byDomain(): Map<string, IRequestRateMetrics>;
  };
  
  // Cumulative totals
  totals: {
    bytesIn(): number;
    bytesOut(): number;
    connections(): number;
  };
  
  // Backend metrics
  backends: {
    byBackend(): Map<string, IBackendMetrics>;
    protocols(): Map<string, string>;
    topByErrors(limit?: number): Array<{ backend: string; errors: number }>;
    detectedProtocols(): IProtocolCacheEntry[];
  };

  // UDP metrics
  udp: {
    activeSessions(): number;
    totalSessions(): number;
    datagramsIn(): number;
    datagramsOut(): number;
  };

  // Performance metrics
  percentiles: {
    connectionDuration(): { p50: number; p95: number; p99: number };
    bytesTransferred(): { 
      in: { p50: number; p95: number; p99: number };
      out: { p50: number; p95: number; p99: number };
    };
  };
}

/**
 * Configuration for metrics collection
 */
export interface IMetricsConfig {
  enabled: boolean;
  
  // Sampling configuration
  sampleIntervalMs: number;        // Default: 1000 (1 second)
  retentionSeconds: number;        // Default: 3600 (1 hour)
  
  // Performance tuning
  enableDetailedTracking: boolean; // Per-connection byte history
  enablePercentiles: boolean;      // Calculate percentiles
  cacheResultsMs: number;          // Cache expensive calculations
  
  // Export configuration
  prometheusEnabled: boolean;
  prometheusPath: string;          // Default: /metrics
  prometheusPrefix: string;        // Default: smartproxy_
}

/**
 * Protocol cache entry from the Rust proxy's auto-detection cache.
 * Shows which protocol (h1/h2/h3) is detected for each backend+domain pair,
 * including failure suppression state with escalating cooldowns.
 */
export interface IProtocolCacheEntry {
  host: string;
  port: number;
  domain: string | null;
  protocol: string;
  h3Port: number | null;
  ageSecs: number;
  lastAccessedSecs: number;
  lastProbedSecs: number;
  h2Suppressed: boolean;
  h3Suppressed: boolean;
  h2CooldownRemainingSecs: number | null;
  h3CooldownRemainingSecs: number | null;
  h2ConsecutiveFailures: number | null;
  h3ConsecutiveFailures: number | null;
}

/**
 * Per-backend metrics
 */
export interface IBackendMetrics {
  protocol: string;
  activeConnections: number;
  totalConnections: number;
  connectErrors: number;
  handshakeErrors: number;
  requestErrors: number;
  avgConnectTimeMs: number;
  poolHitRate: number;
  h2Failures: number;
}

/**
 * Internal interface for connection byte tracking
 */
export interface IByteTracker {
  connectionId: string;
  routeName: string;
  remoteIP: string;
  bytesIn: number;
  bytesOut: number;
  startTime: number;
  lastUpdate: number;
}
