import test from "node:test"
import assert from "node:assert/strict"
import fs from "node:fs"

const hookSource = fs.readFileSync("hooks/use-performance-data.ts", "utf8")
const systemSource = fs.readFileSync("hooks/use-system.ts", "utf8")
const permissionsSource = fs.readFileSync("hooks/use-permissions.tsx", "utf8")
const pageSource = fs.readFileSync("app/(dashboard)/status/page.tsx", "utf8")
const serverSource = fs.readFileSync("app/(dashboard)/_components/performance-server-list.tsx", "utf8")
const usageSource = fs.readFileSync("app/(dashboard)/_components/performance-usage-card.tsx", "utf8")
const healthSource = fs.readFileSync("app/(dashboard)/_components/performance-infrastructure-card.tsx", "utf8")
const backendSource = fs.readFileSync("app/(dashboard)/_components/performance-backend-card.tsx", "utf8")
const statusSourcesSource = fs.readFileSync("app/(dashboard)/_components/performance-status-sources.tsx", "utf8")

test("performance refresh keeps partial data and rejects stale responses", () => {
  assert.match(hookSource, /Promise\.allSettled/)
  assert.match(hookSource, /requestVersionRef/)
  assert.match(hookSource, /sourceErrors/)
  assert.match(hookSource, /lastUpdatedAt/)
  assert.match(hookSource, /metricsUpdatedAt/)
  assert.match(hookSource, /diagnosticsInfo/)
  assert.match(hookSource, /usageUpdatedAt/)
  assert.match(hookSource, /getClusterSnapshot/)
  assert.match(hookSource, /adminDiscovery\?\.clusterSnapshot/)
  assert.match(hookSource, /diagnosticsError/)
  assert.match(hookSource, /refreshDiagnostics\(diagnosticsPath, requestVersion\)/)
  assert.match(hookSource, /Cluster diagnostics timed out\./)
  assert.match(hookSource, /setMetricsUpdatedAt\(new Date\(\)\)/)
  assert.match(hookSource, /refreshing/)
  assert.match(hookSource, /new AbortController/)
  assert.match(hookSource, /controller\.abort/)
  assert.match(hookSource, /document\.visibilityState/)
  assert.match(hookSource, /hasSystemDataRef\.current = false[\s\S]*setSystemInfo\(\{\}\)/)
  assert.doesNotMatch(hookSource, /setLoading\(false\)[\s\S]*getSystemMetrics/)
  assert.ok((systemSource.match(/suppress403Redirect: true/g) ?? []).length >= 3)
})

test("cluster diagnostics are optional and use only the discovered admin path", () => {
  assert.match(systemSource, /getClusterSnapshot/)
  assert.match(systemSource, /api\.get\(api\.resolveUrl\(path\)/)
  assert.match(systemSource, /suppress403Redirect: true/)
  assert.doesNotMatch(systemSource, /getClusterSnapshot[\s\S]*?https?:\/\//)
  assert.doesNotMatch(hookSource, /Promise\.allSettled\(\[[\s\S]*getClusterSnapshot[\s\S]*\]\)/)
  assert.doesNotMatch(hookSource, /InvalidAccessKeyId|BrokenPipe/)
})

test("running status skips Strict Mode preview requests", () => {
  assert.match(hookSource, /scheduleMicrotask\(\(\) => \{\s*if \(!cancelled\) void refetch\(\)/)
  assert.match(hookSource, /return \(\) => \{\s*cancelled = true/)
  assert.match(permissionsSource, /scheduleMicrotask\(\(\) => \{\s*if \(!cancelled\) void fetchAdminStatus\(\)/)
})

test("running status distinguishes unknown values and exposes recovery feedback", () => {
  assert.match(pageSource, /role="alert"/)
  assert.match(pageSource, /aria-busy=\{refreshing\}/)
  assert.match(pageSource, /lastUpdatedAt/)
  assert.match(pageSource, /sourceErrors/)
  assert.match(pageSource, /order-2 xl:order-3 xl:col-span-2/)
  assert.match(pageSource, /isScannerCycleActive\(metricsInfo\)/)
  assert.match(pageSource, /t\("Scanner Status"\)/)
  assert.doesNotMatch(pageSource, /dayjs\(last\)/)
  assert.doesNotMatch(pageSource, /t\("Uptime"\)/)
  assert.doesNotMatch(pageSource, /t\("Current Scan Started"\)/)
})

test("server health is textual, filterable, and usable on narrow screens", () => {
  assert.match(serverSource, /aria-pressed=/)
  assert.match(serverSource, /<Badge/)
  assert.match(serverSource, /unknown/)
  assert.match(serverSource, /min-h-11/)
  assert.match(serverSource, /overflow-wrap:anywhere/)
  assert.match(serverSource, /grid gap-3 md:grid-cols-2/)
  assert.match(serverSource, /No servers match the current filter/)
  assert.match(serverSource, /stateCounts\[state\] > 0 \|\| filterBy === state/)
  assert.match(serverSource, /reportedServers\.length === 0/)
  assert.doesNotMatch(serverSource, /<ScrollArea/)
  assert.doesNotMatch(serverSource, /dayjs\(\)\.subtract/)
})

test("status sections expose semantic headings and named progress", () => {
  assert.match(usageSource, /<h2/)
  assert.match(usageSource, /aria-label=/)
  assert.match(healthSource, /<h2/)
  assert.match(healthSource, /Needs attention/)
  assert.match(healthSource, /serverCounts\.some/)
  assert.match(healthSource, /diskCounts\.some/)
  assert.match(healthSource, /unavailableLabel/)
  assert.match(backendSource, /<h2/)
  assert.match(backendSource, /Storage Configuration/)
  assert.match(statusSourcesSource, /<h2/)
  assert.match(statusSourcesSource, /<Collapsible/)
  assert.match(statusSourcesSource, /<CollapsibleTrigger/)
  assert.match(statusSourcesSource, /<CollapsibleContent/)
  assert.match(statusSourcesSource, /if \(!diagnostics\) return null/)
  assert.match(statusSourcesSource, /\["degraded", "stale", "unknown"\]\.includes\(diagnostic\.state\)/)
  assert.match(statusSourcesSource, /open=\{open\}/)
  assert.match(statusSourcesSource, /onOpenChange=\{setOpen\}/)
  assert.match(statusSourcesSource, /hasAttention && !previousHasAttention\.current/)
  assert.match(statusSourcesSource, /Diagnostic Details/)
  assert.match(statusSourcesSource, /Diagnostic items need confirmation/)
  assert.match(statusSourcesSource, /Peer Health/)
  assert.match(statusSourcesSource, /Storage Readiness/)
  assert.match(statusSourcesSource, /Usage Freshness/)
  assert.match(statusSourcesSource, /Listing and Metacache/)
  assert.match(statusSourcesSource, /Workload Admission/)
  assert.match(statusSourcesSource, /Not reported/)
  assert.match(statusSourcesSource, /Historical internode stall timeouts/)
  assert.match(statusSourcesSource, /issuecomment-5040442761/)
  assert.match(statusSourcesSource, /<Badge/)
  assert.match(statusSourcesSource, /<Separator/)
  assert.match(statusSourcesSource, /Correlate time-windowed walk_dir metrics and metacache logs/)
  assert.doesNotMatch(statusSourcesSource, /const notReported/)
  assert.ok(pageSource.indexOf("<PerformanceServerList") < pageSource.indexOf("<PerformanceStatusSources"))
})

test("running status uses backend usable free capacity without synthesizing it", () => {
  assert.match(pageSource, /totalFreeCapacity=\{totalFreeCapacity\}/)
  assert.match(usageSource, /totalFreeCapacity === undefined \? "--" : formatCapacity\(totalFreeCapacity\)/)
  assert.match(usageSource, /Usable Capacity Used/)
  assert.doesNotMatch(usageSource, /totalCapacity\s*-\s*totalUsedCapacity/)
})
