/**
 * Shared status / threshold business rules for the Executive dashboard.
 *
 * These are the single source of truth for every health color, status pill,
 * and trend delta across all screens (README "Status thresholds" section).
 * Keep them here — do NOT re-derive thresholds inline in components.
 */
import type { StatusLevel } from './types';

/** Uptime %: ≥99.9 healthy · 99–99.9 warning · <99 critical. */
export function uptimeStatus(uptime: number): StatusLevel {
    if (uptime >= 99.9) return 'healthy';
    if (uptime >= 99) return 'warning';
    return 'critical';
}

/** Response ms: <200 healthy · <500 warning · ≥500 critical. */
export function responseStatus(ms: number): StatusLevel {
    if (ms < 200) return 'healthy';
    if (ms < 500) return 'warning';
    return 'critical';
}

/** Global health score 0–100: ≥90 healthy · 70–90 warning · <70 critical. */
export function healthStatus(score: number): StatusLevel {
    if (score >= 90) return 'healthy';
    if (score >= 70) return 'warning';
    return 'critical';
}

const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n));

/**
 * Global Health score (0–100). Per README:
 *   round(clamp((uptime-99)*100 - min(incidents*1.5,12) + respBonus, 0, 100))
 * where respBonus = resp<250 ? 5 : resp<500 ? 2 : 0.
 * With mock data this yields 96.
 */
export function healthScore(uptime: number, incidents: number, avgResponseMs: number): number {
    const respBonus = avgResponseMs < 250 ? 5 : avgResponseMs < 500 ? 2 : 0;
    const raw = (uptime - 99) * 100 - Math.min(incidents * 1.5, 12) + respBonus;
    return Math.round(clamp(raw, 0, 100));
}

/**
 * Trend deltas are colored by GOODNESS, not direction. Each metric has a
 * "good direction"; return whether a given delta is good (→ green) or bad
 * (→ red). `goodWhen` is the sign that is good: 'up' (e.g. uptime) or
 * 'down' (e.g. incidents, response time).
 */
export function deltaIsGood(delta: number, goodWhen: 'up' | 'down'): boolean {
    if (delta === 0) return true; // flat = neutral-good (no regression)
    return goodWhen === 'up' ? delta > 0 : delta < 0;
}

/** Compact relative-time formatter ("3m", "2h", "5d", "just now"). */
export function relTime(iso: string, now: number = Date.now()): string {
    const diffMs = now - new Date(iso).getTime();
    if (diffMs < 0) return 'just now';
    const s = Math.floor(diffMs / 1000);
    if (s < 60) return 'just now';
    const m = Math.floor(s / 60);
    if (m < 60) return `${m}m ago`;
    const h = Math.floor(m / 60);
    if (h < 24) return `${h}h ago`;
    const d = Math.floor(h / 24);
    return `${d}d ago`;
}
