/**
 * VF — real alerting evaluator (honesty pass B).
 *
 * In-process harness (injected metrics → no DB). Proves the on-demand evaluator is
 * real + honest:
 *   Leg 1  error-rate both-dir + severity escalation (warn/crit/emerg)
 *   Leg 2  p95 latency both-dir
 *   Leg 3  restart both-dir (uptime below window fires; normal uptime doesn't)
 *   Leg 4  k8s-skip HONESTY leg — planned rules skipped, NOT evaluated, NOT cleared
 *   Leg 5  deterministic — same metrics → identical result (anti-fabrication)
 *
 * Exit 0 iff all pass.
 */

import { alertingThresholds } from "../server/lib/enterprise-alerting";
import type { CurrentMetrics } from "../server/lib/pilot-readiness-extras-8";

const BASE: CurrentMetrics = {
  uptimeSec: 100000, totalRequests: 1000, errorRatePct: 0, p95LatencyMs: 50,
  aiDecisionsTotal: 0, threatEventsTotal: 0,
};
const K8S = ["RULE-HPA-001", "RULE-POD-001", "RULE-NODE-001"];

const evalWith = (o: Partial<CurrentMetrics>) => alertingThresholds.evaluateRules({ ...BASE, ...o });
const sevOf = (r: Awaited<ReturnType<typeof evalWith>>, ruleId: string) =>
  r.fired.find((f) => f.ruleId === ruleId)?.severity;

type Leg = { name: string; pass: boolean; detail: string };
const legs: Leg[] = [];
const rec = (name: string, pass: boolean, detail: string) => legs.push({ name, pass, detail });

async function main() {
  // Leg 1 — error-rate both-directions + severity escalation
  {
    const warn = await evalWith({ errorRatePct: 7 });
    const crit = await evalWith({ errorRatePct: 15 });
    const emerg = await evalWith({ errorRatePct: 30 });
    const clear = await evalWith({ errorRatePct: 1 });
    const ok =
      sevOf(warn, "RULE-OPS-ERR") === "WARNING" &&
      sevOf(crit, "RULE-OPS-ERR") === "CRITICAL" &&
      sevOf(emerg, "RULE-OPS-ERR") === "EMERGENCY" &&
      sevOf(clear, "RULE-OPS-ERR") === undefined;
    rec("Leg 1 error-rate both-dir + escalation", ok, `7%→WARNING, 15%→CRITICAL, 30%→EMERGENCY, 1%→no-fire`);
  }

  // Leg 2 — p95 latency both-directions
  {
    const hi = await evalWith({ p95LatencyMs: 1500 });
    const lo = await evalWith({ p95LatencyMs: 100 });
    const ok = sevOf(hi, "RULE-OPS-LAT") === "CRITICAL" && sevOf(lo, "RULE-OPS-LAT") === undefined;
    rec("Leg 2 p95 latency both-dir", ok, `1500ms→CRITICAL, 100ms→no-fire`);
  }

  // Leg 3 — restart both-directions (below window fires)
  {
    const restarted = await evalWith({ uptimeSec: 60 });
    const stable = await evalWith({ uptimeSec: 100000 });
    const ok = sevOf(restarted, "RULE-OPS-RESTART") === "WARNING" && sevOf(stable, "RULE-OPS-RESTART") === undefined;
    rec("Leg 3 restart both-dir", ok, `uptime 60s→WARNING (restarted), 100000s→no-fire`);
  }

  // Leg 4 — k8s-skip HONESTY leg: planned rules skipped, never evaluated, never cleared
  {
    const r = await evalWith({ errorRatePct: 99, p95LatencyMs: 9999, uptimeSec: 1 }); // everything red
    const allSkipped = K8S.every((id) => r.skippedPlanned.includes(id));
    const noneEvaluated = K8S.every((id) => !r.evaluated.includes(id));
    const noneFired = K8S.every((id) => !r.fired.some((f) => f.ruleId === id));
    rec("Leg 4 k8s-skip honesty (never cleared)", allSkipped && noneEvaluated && noneFired,
      `k8s ${K8S.length} in skippedPlanned, 0 evaluated, 0 fired — planned≠OK even under all-red metrics`);
  }

  // Leg 5 — deterministic
  {
    const a = await evalWith({ errorRatePct: 12, p95LatencyMs: 800 });
    const b = await evalWith({ errorRatePct: 12, p95LatencyMs: 800 });
    const key = (r: Awaited<ReturnType<typeof evalWith>>) =>
      JSON.stringify({ evaluated: r.evaluated, fired: r.fired, skippedPlanned: r.skippedPlanned });
    rec("Leg 5 deterministic", key(a) === key(b), `same metrics → identical evaluated/fired/skippedPlanned`);
  }

  console.log("\n=== VF alerting evaluator (B) ===\n");
  let failed = 0;
  for (const l of legs) {
    console.log(`${l.pass ? "PASS" : "FAIL"}  ${l.name} — ${l.detail}`);
    if (!l.pass) failed++;
  }
  console.log(`\n${legs.length - failed}/${legs.length} legs passed.`);
  if (failed > 0) { console.log(`\nGATE: FAIL (${failed})`); process.exit(1); }
  console.log("\nGATE: GREEN — real rules fire/clear correctly (both-dir + escalation), k8s planned skipped-not-cleared, deterministic.");
}

main().catch((e) => { console.error("HARNESS ERROR:", e); process.exit(1); });
