Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

51.6 KB
Raw Blame
import type { UnifiedFinding } from '@/stores/aiIntelligence';
import type { ApprovalRequest } from '@/api/ai';
import type { InvestigationOutcome, InvestigationStatus } from '@/api/patrol';
import type { MetadataBadgeTone } from '@/components/shared/MetadataBadge';
import { isLivePendingApproval } from '@/utils/approvalState';
import { getPatrolProviderSettingsAction } from '@/utils/patrolRuntimeActions';
import { formatIdentifierLabel, titleCaseDelimitedLabel } from '@/utils/textPresentation';
import { formatAbsoluteTime, formatBytes, formatTimeUntil } from '@/utils/format';

const DEFAULT_BADGE_CLASSES = 'border-border bg-surface-alt text-muted';
const DEFAULT_LOOP_STATE_CLASSES = 'border-border bg-surface-alt text-muted';
const DEFAULT_FINDING_STATUS_LABEL = 'Dismissed';
const DEFAULT_BADGE_TONE: MetadataBadgeTone = 'muted';

const FINDING_SOURCE_LABELS: Record<string, string> = {
  threshold: 'Alert',
  'ai-patrol': 'Pulse Patrol',
  anomaly: 'Anomaly',
  'ai-chat': 'Pulse Assistant',
  correlation: 'Correlation',
  forecast: 'Forecast',
};

const FINDING_SOURCE_CLASSES: Record<string, string> = {
  threshold:
    'border-orange-200 bg-orange-50 text-orange-700 dark:border-orange-800 dark:bg-orange-900 dark:text-orange-300',
  'ai-patrol':
    'border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-900/25 dark:text-blue-300',
  anomaly:
    'border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-900/25 dark:text-blue-300',
  'ai-chat':
    'border-teal-200 bg-teal-50 text-teal-700 dark:border-teal-800 dark:bg-teal-900/25 dark:text-teal-300',
  correlation:
    'border-sky-200 bg-sky-50 text-sky-700 dark:border-sky-800 dark:bg-sky-900/25 dark:text-sky-300',
  forecast:
    'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-900/25 dark:text-emerald-300',
};

const FINDING_SOURCE_TONES: Record<string, MetadataBadgeTone> = {
  threshold: 'orange',
  'ai-patrol': 'info',
  anomaly: 'info',
  'ai-chat': 'teal',
  correlation: 'sky',
  forecast: 'success',
};

const FINDING_SEVERITY_CLASSES: Record<string, string> = {
  critical:
    'border-red-200 bg-red-50 text-red-700 dark:border-red-800 dark:bg-red-900/25 dark:text-red-300',
  warning:
    'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-900/25 dark:text-amber-300',
  info: 'border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-900/25 dark:text-blue-300',
  watch: 'border-border bg-surface-alt text-base-content',
};

const FINDING_SEVERITY_TONES: Record<string, MetadataBadgeTone> = {
  critical: 'danger',
  warning: 'warning',
  info: 'info',
  watch: 'neutral',
};

const FINDING_SEVERITY_TONE_CLASSES: Record<string, string> = {
  critical: 'bg-red-100 text-red-700 dark:bg-red-900/25 dark:text-red-300',
  warning: 'bg-amber-100 text-amber-700 dark:bg-amber-900/25 dark:text-amber-300',
  info: 'bg-blue-100 text-blue-700 dark:bg-blue-900/25 dark:text-blue-300',
  watch: 'bg-surface-alt text-base-content',
};

const INVESTIGATION_STATUS_CLASSES: Record<InvestigationStatus, string> = {
  pending: 'border-border bg-surface-alt text-muted',
  running:
    'border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-900/25 dark:text-blue-300',
  completed:
    'border-green-200 bg-green-50 text-green-700 dark:border-green-800 dark:bg-green-900/25 dark:text-green-300',
  failed:
    'border-red-200 bg-red-50 text-red-700 dark:border-red-800 dark:bg-red-900/25 dark:text-red-300',
  needs_attention:
    'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-900/25 dark:text-amber-300',
};

const INVESTIGATION_STATUS_TONES: Record<InvestigationStatus, MetadataBadgeTone> = {
  pending: 'muted',
  running: 'info',
  completed: 'success',
  failed: 'danger',
  needs_attention: 'warning',
};

const INVESTIGATION_STATUS_LABELS: Record<InvestigationStatus, string> = {
  pending: 'Pending',
  running: 'Running',
  completed: 'Completed',
  failed: 'Failed',
  needs_attention: 'Needs Attention',
};

const FINDING_LOOP_STATE_CLASSES: Record<string, string> = {
  detected:
    'border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-900/25 dark:text-blue-300',
  investigating:
    'border-indigo-200 bg-indigo-50 text-indigo-700 dark:border-indigo-800 dark:bg-indigo-900/25 dark:text-indigo-300',
  remediation_planned:
    'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-900/25 dark:text-amber-300',
  remediating:
    'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-900/25 dark:text-amber-300',
  remediation_failed:
    'border-red-200 bg-red-50 text-red-700 dark:border-red-800 dark:bg-red-900/25 dark:text-red-300',
  needs_attention:
    'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-900/25 dark:text-amber-300',
  timed_out: 'border-border bg-surface-alt text-base-content',
  resolved:
    'border-green-200 bg-green-50 text-green-700 dark:border-green-800 dark:bg-green-900/25 dark:text-green-300',
  dismissed: 'border-border bg-surface-alt text-muted',
  snoozed:
    'border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-900/25 dark:text-blue-300',
  suppressed: 'border-border bg-surface-alt text-muted',
};

const FINDING_LOOP_STATE_TONES: Record<string, MetadataBadgeTone> = {
  detected: 'info',
  investigating: 'indigo',
  remediation_planned: 'warning',
  remediating: 'warning',
  remediation_failed: 'danger',
  needs_attention: 'warning',
  timed_out: 'neutral',
  resolved: 'success',
  dismissed: 'muted',
  snoozed: 'info',
  suppressed: 'muted',
};

const FINDING_LIFECYCLE_LABELS: Record<string, string> = {
  detected: 'Detected',
  regressed: 'Regressed',
  acknowledged: 'Acknowledged',
  snoozed: 'Snoozed',
  unsnoozed: 'Unsnoozed',
  dismissed: 'Dismissed',
  undismissed: 'Undismissed',
  suppressed: 'Suppressed',
  resolved: 'Resolved',
  auto_resolved: 'Auto-resolved',
  verification_passed: 'Fix verified',
  investigation_updated: 'Investigation updated',
  investigation_outcome: 'Investigation outcome',
  user_note_updated: 'Note updated',
  loop_state: 'Loop state changed',
  seen_while_suppressed: 'Seen while suppressed',
  loop_transition_violation: 'Invalid transition blocked',
  content_replaced: 'Re-detected with different details',
};

const FINDING_STATUS_BADGE_CLASSES: Record<string, string> = {
  resolved:
    'border-green-200 bg-green-50 text-green-700 dark:border-green-800 dark:bg-green-900/25 dark:text-green-300',
  snoozed:
    'border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-900/25 dark:text-blue-300',
  dismissed: DEFAULT_BADGE_CLASSES,
};

const FINDING_STATUS_BADGE_TONES: Record<string, MetadataBadgeTone> = {
  resolved: 'success',
  snoozed: 'info',
  dismissed: 'muted',
};

const FINDING_STATUS_LABELS: Record<string, string> = {
  resolved: 'Resolved',
  snoozed: 'Snoozed',
  dismissed: 'Dismissed',
};

const INVESTIGATION_OUTCOME_LABELS: Record<InvestigationOutcome, string> = {
  resolved: 'Resolved',
  fix_queued: 'Fix queued',
  fix_executed: 'Fix applied',
  fix_failed: 'Fix failed',
  fix_rejected: 'Fix rejected',
  needs_attention: 'Needs attention',
  cannot_fix: 'Cannot remediate',
  timed_out: 'Timed out',
  unclassified: 'No clear conclusion',
  interrupted: 'Interrupted — will retry',
  fix_verified: 'Fix verified',
  fix_verification_failed: 'Verification failed',
  fix_verification_unknown: 'Verification unknown',
};

const INVESTIGATION_OUTCOME_CLASSES: Record<InvestigationOutcome, string> = {
  resolved:
    'border-green-200 bg-green-50 text-green-700 dark:border-green-800 dark:bg-green-900/25 dark:text-green-300',
  fix_queued:
    'border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-900/25 dark:text-blue-300',
  fix_executed:
    'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-900/25 dark:text-emerald-300',
  fix_failed:
    'border-red-200 bg-red-50 text-red-700 dark:border-red-800 dark:bg-red-900/25 dark:text-red-300',
  fix_rejected:
    'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-900/25 dark:text-amber-300',
  needs_attention:
    'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-900/25 dark:text-amber-300',
  cannot_fix: 'border-border bg-surface-alt text-muted',
  timed_out: 'border-border bg-surface-alt text-base-content',
  unclassified:
    'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-900/25 dark:text-amber-300',
  interrupted: 'border-border bg-surface-alt text-base-content',
  fix_verified:
    'border-green-200 bg-green-50 text-green-700 dark:border-green-800 dark:bg-green-900/25 dark:text-green-300',
  fix_verification_failed:
    'border-red-200 bg-red-50 text-red-700 dark:border-red-800 dark:bg-red-900/25 dark:text-red-300',
  fix_verification_unknown:
    'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-900/25 dark:text-amber-300',
};

const INVESTIGATION_OUTCOME_TONES: Record<InvestigationOutcome, MetadataBadgeTone> = {
  resolved: 'success',
  fix_queued: 'info',
  fix_executed: 'success',
  fix_failed: 'danger',
  fix_rejected: 'warning',
  needs_attention: 'warning',
  cannot_fix: 'muted',
  timed_out: 'neutral',
  unclassified: 'warning',
  interrupted: 'neutral',
  fix_verified: 'success',
  fix_verification_failed: 'danger',
  fix_verification_unknown: 'warning',
};

const FINDING_SEVERITY_SORT_ORDER: Record<string, number> = {
  critical: 0,
  warning: 1,
  watch: 2,
  info: 3,
};

const FINDING_RESOURCE_CRITICALITY_SORT_ORDER: Record<string, number> = {
  high: 0,
  medium: 1,
  '': 2,
  low: 3,
};

const FINDING_SEVERITY_COMPACT_LABELS: Record<string, string> = {
  critical: 'CRIT',
  warning: 'WARN',
  watch: 'WATCH',
  info: 'INFO',
};

const INVESTIGATION_OUTCOME_SORT_ORDER: Record<string, number> = {
  fix_verification_failed: 0,
  fix_failed: 0,
  fix_verification_unknown: 1,
  fix_rejected: 1,
  timed_out: 1,
  needs_attention: 1,
  cannot_fix: 1,
  unclassified: 1,
  fix_queued: 2,
};

export type FindingsFilter = 'all' | 'active' | 'resolved' | 'approvals' | 'attention';

export interface FindingFilterOption {
  value: FindingsFilter;
  label: string;
  tone?: 'default' | 'warning';
  count?: number;
}

export interface FindingEmptyStateCopy {
  title: string;
  body?: string;
}

export interface FindingRecencyPresentation {
  label: string;
  timestamp: string;
}

export interface FindingCountdownPresentation {
  label: string;
  title: string;
}

export interface PatrolFindingClassification {
  kind: 'runtime' | 'infrastructure';
  label: string;
  badgeClasses: string;
}

export interface FindingSubjectPresentation {
  label: string;
}

export interface FindingTitlePresentation {
  label: string;
}

export interface FindingPrimaryActionPresentation {
  label: string;
  href: string;
}

export interface FindingManualControlsPresentation {
  acknowledge: boolean;
  snooze: boolean;
  dismiss: boolean;
}

export interface PatrolFindingsBadgePresentation {
  tone: 'danger' | 'warning' | 'info' | 'muted';
}

export interface PatrolFindingDisplayGroup<TFinding> {
  id: string;
  affectedResourceCount: number;
  kind: 'correlated' | 'finding' | 'node' | 'resource';
  label: string;
  primaryFinding: TFinding;
  relatedFindings: TFinding[];
  findings: TFinding[];
}

export interface FindingSeverityPresentation {
  label: string;
  badgeClasses: string;
  badgeTone: MetadataBadgeTone;
  uppercase: boolean;
}

export interface FindingCompactBadgePresentation {
  label: string;
  badgeClasses: string;
}

export type FindingPatrolWorkflowStage =
  'investigating' | 'approval' | 'verification' | 'attention' | 'recorded' | 'paused';

export interface FindingPatrolWorkflowPresentation {
  stage: FindingPatrolWorkflowStage;
  label: string;
  detail: string;
  tone: MetadataBadgeTone;
}

export const getFindingSourceLabel = (source: UnifiedFinding['source'] | string): string =>
  FINDING_SOURCE_LABELS[source] || source;

export const getFindingSourceBadgeClasses = (source: UnifiedFinding['source'] | string): string =>
  FINDING_SOURCE_CLASSES[source] || FINDING_SOURCE_CLASSES['ai-patrol'];

export const getFindingSourceBadgeTone = (
  source: UnifiedFinding['source'] | string,
): MetadataBadgeTone => FINDING_SOURCE_TONES[source] || FINDING_SOURCE_TONES['ai-patrol'];

export const getFindingSeverityBadgeClasses = (
  severity: UnifiedFinding['severity'] | string,
): string => FINDING_SEVERITY_CLASSES[severity] || DEFAULT_BADGE_CLASSES;

export const getFindingSeverityBadgeTone = (
  severity: UnifiedFinding['severity'] | string,
): MetadataBadgeTone => FINDING_SEVERITY_TONES[severity] || DEFAULT_BADGE_TONE;

export const getFindingSeverityPresentation = (
  finding: Pick<UnifiedFinding, 'severity' | 'resourceId' | 'resourceName' | 'title'>,
): FindingSeverityPresentation => {
  if (!isPatrolRuntimeFinding(finding)) {
    return {
      label: String(finding.severity),
      badgeClasses: getFindingSeverityBadgeClasses(finding.severity),
      badgeTone: getFindingSeverityBadgeTone(finding.severity),
      uppercase: true,
    };
  }

  if (finding.severity === 'critical') {
    return {
      label: 'Runtime critical',
      badgeClasses:
        'border-red-200 bg-red-50 text-red-700 dark:border-red-800 dark:bg-red-900/25 dark:text-red-300',
      badgeTone: 'danger',
      uppercase: false,
    };
  }

  return {
    label: 'Runtime issue',
    badgeClasses:
      'border-sky-200 bg-sky-50 text-sky-700 dark:border-sky-800 dark:bg-sky-900/25 dark:text-sky-300',
    badgeTone: 'sky',
    uppercase: false,
  };
};

export const getFindingStatusBadgeClasses = (status: string): string =>
  FINDING_STATUS_BADGE_CLASSES[status] || DEFAULT_BADGE_CLASSES;

export const getFindingStatusBadgeTone = (status: string): MetadataBadgeTone =>
  FINDING_STATUS_BADGE_TONES[status] || DEFAULT_BADGE_TONE;

export const getFindingStatusLabel = (status: string): string =>
  FINDING_STATUS_LABELS[status] || DEFAULT_FINDING_STATUS_LABEL;

export const getFindingSeverityToneClasses = (
  severity: UnifiedFinding['severity'] | string,
): string => FINDING_SEVERITY_TONE_CLASSES[severity] || 'bg-surface-alt text-muted';

export const getFindingSeveritySortOrder = (
  severity: UnifiedFinding['severity'] | string,
): number => FINDING_SEVERITY_SORT_ORDER[severity] ?? 4;

export const getFindingResourceCriticalitySortOrder = (
  criticality: UnifiedFinding['resourceCriticality'] | string | undefined,
): number => {
  const normalized = String(criticality || '')
    .trim()
    .toLowerCase();
  return FINDING_RESOURCE_CRITICALITY_SORT_ORDER[normalized] ?? 2;
};

export const getFindingActiveRuntimeSortOrder = (
  finding: Pick<UnifiedFinding, 'status' | 'resourceId' | 'resourceName' | 'title'>,
): number => (finding.status === 'active' && isPatrolRuntimeFinding(finding) ? 0 : 1);

export const getPatrolFindingsBadgePresentation = (
  findings: Pick<UnifiedFinding, 'status' | 'severity' | 'resourceId' | 'resourceName' | 'title'>[],
): PatrolFindingsBadgePresentation => {
  const activeFindings = findings.filter((finding) => finding.status === 'active');
  if (
    activeFindings.some(
      (finding) => finding.severity === 'critical' && !isPatrolRuntimeFinding(finding),
    )
  ) {
    return { tone: 'danger' };
  }
  if (
    activeFindings.some(
      (finding) => finding.severity === 'critical' && isPatrolRuntimeFinding(finding),
    )
  ) {
    return { tone: 'info' };
  }
  if (
    activeFindings.some(
      (finding) => finding.severity === 'warning' && !isPatrolRuntimeFinding(finding),
    )
  ) {
    return { tone: 'warning' };
  }
  if (
    activeFindings.some(
      (finding) => finding.severity === 'warning' && isPatrolRuntimeFinding(finding),
    )
  ) {
    return { tone: 'info' };
  }

  return { tone: 'muted' };
};

export const getFindingSeverityCompactLabel = (
  severity: UnifiedFinding['severity'] | string,
): string => FINDING_SEVERITY_COMPACT_LABELS[severity] || String(severity).toUpperCase();

export const isPatrolRuntimeFinding = (
  finding: Pick<UnifiedFinding, 'resourceId' | 'resourceName' | 'title'>,
): boolean => {
  const resourceId = String(finding.resourceId || '')
    .trim()
    .toLowerCase();
  const resourceName = String(finding.resourceName || '')
    .trim()
    .toLowerCase();
  const title = String(finding.title || '')
    .trim()
    .toLowerCase();

  return (
    resourceId === 'ai-service' ||
    resourceName === 'pulse patrol service' ||
    title.startsWith('pulse patrol:')
  );
};

export const normalizePatrolRuntimeFindingLabel = (title: string | undefined): string => {
  const rawTitle = String(title || '').trim();
  const normalizedTitle = rawTitle.replace(/^Pulse Patrol:\s*/i, '').trim();

  if (/^insufficient api credits$/i.test(normalizedTitle)) {
    return 'Provider billing or quota issue';
  }

  return normalizedTitle || rawTitle;
};

export const getPatrolFindingClassification = (
  finding: Pick<UnifiedFinding, 'resourceId' | 'resourceName' | 'title'>,
): PatrolFindingClassification =>
  isPatrolRuntimeFinding(finding)
    ? {
        kind: 'runtime',
        label: 'Patrol runtime',
        badgeClasses:
          'border-sky-200 bg-sky-50 text-sky-700 dark:border-sky-800 dark:bg-sky-900/25 dark:text-sky-300',
      }
    : {
        kind: 'infrastructure',
        label: 'Infrastructure',
        badgeClasses: DEFAULT_BADGE_CLASSES,
      };

export const getFindingSubjectPresentation = (
  finding: Pick<UnifiedFinding, 'resourceId' | 'resourceName' | 'resourceType' | 'title'>,
): FindingSubjectPresentation => {
  if (isPatrolRuntimeFinding(finding)) {
    return { label: 'Patrol runtime' };
  }

  const resourceName =
    String(finding.resourceName || '').trim() || String(finding.resourceId || '').trim();
  const resourceType = String(finding.resourceType || '').trim();

  if (!resourceType) {
    return { label: resourceName };
  }

  return {
    label: `${resourceName} (${formatIdentifierLabel(resourceType)})`,
  };
};

export const getPatrolFindingResourceGroupKey = (
  finding: Pick<UnifiedFinding, 'id' | 'resourceId' | 'resourceName' | 'resourceType' | 'title'>,
): string => {
  const resourceId = String(finding.resourceId || '').trim();
  if (resourceId) {
    return `id:${resourceId.toLowerCase()}`;
  }

  const resourceName = String(finding.resourceName || '').trim();
  const resourceType = String(finding.resourceType || '').trim();
  if (resourceName || resourceType) {
    return `subject:${getFindingSubjectPresentation(finding).label.toLowerCase()}`;
  }

  return `finding:${finding.id}`;
};

export function buildPatrolFindingDisplayGroups<
  TFinding extends Pick<
    UnifiedFinding,
    | 'correlatedFindingIds'
    | 'id'
    | 'node'
    | 'resourceId'
    | 'resourceName'
    | 'resourceType'
    | 'title'
  >,
>(findings: readonly TFinding[]): PatrolFindingDisplayGroup<TFinding>[] {
  const findingById = new Map(findings.map((finding) => [finding.id, finding]));
  const parentById = new Map(findings.map((finding) => [finding.id, finding.id]));

  const findRoot = (findingId: string): string => {
    const parent = parentById.get(findingId) ?? findingId;
    if (parent === findingId) return parent;
    const root = findRoot(parent);
    parentById.set(findingId, root);
    return root;
  };
  const union = (leftId: string, rightId: string) => {
    const leftRoot = findRoot(leftId);
    const rightRoot = findRoot(rightId);
    if (leftRoot !== rightRoot) parentById.set(rightRoot, leftRoot);
  };

  const firstIdByResource = new Map<string, string>();
  const firstIdByNode = new Map<string, string>();
  for (const finding of findings) {
    const resourceKey = getPatrolFindingResourceGroupKey(finding);
    const firstResourceId = firstIdByResource.get(resourceKey);
    if (firstResourceId) union(firstResourceId, finding.id);
    else firstIdByResource.set(resourceKey, finding.id);

    const node = String(finding.node || '').trim();
    if (node) {
      const nodeKey = node.toLowerCase();
      const firstNodeId = firstIdByNode.get(nodeKey);
      if (firstNodeId) union(firstNodeId, finding.id);
      else firstIdByNode.set(nodeKey, finding.id);
    }

    for (const correlatedId of finding.correlatedFindingIds ?? []) {
      if (findingById.has(correlatedId)) union(finding.id, correlatedId);
    }
  }

  const componentByRoot = new Map<string, TFinding[]>();
  for (const finding of findings) {
    const root = findRoot(finding.id);
    const component = componentByRoot.get(root);
    if (component) component.push(finding);
    else componentByRoot.set(root, [finding]);
  }

  return [...componentByRoot.values()].map((component) => {
    const primaryFinding = component[0];
    const resourceKeys = new Set(component.map(getPatrolFindingResourceGroupKey));
    const nodes = new Set(
      component.map((finding) => String(finding.node || '').trim()).filter(Boolean),
    );
    const componentIds = new Set(component.map((finding) => finding.id));
    const hasExplicitCorrelation = component.some((finding) =>
      (finding.correlatedFindingIds ?? []).some((id) => componentIds.has(id)),
    );
    const kind: PatrolFindingDisplayGroup<TFinding>['kind'] =
      component.length === 1
        ? 'finding'
        : hasExplicitCorrelation
          ? 'correlated'
          : resourceKeys.size === 1
            ? 'resource'
            : nodes.size === 1
              ? 'node'
              : 'correlated';
    const commonNode = nodes.size === 1 ? [...nodes][0] : '';
    const label =
      kind === 'finding' || kind === 'resource'
        ? getFindingSubjectPresentation(primaryFinding).label
        : (commonNode ? titleCaseDelimitedLabel(commonNode, { preserveShortAllCaps: true }) : '') ||
          `${resourceKeys.size} related ${resourceKeys.size === 1 ? 'resource' : 'resources'}`;

    return {
      id: `group:${component.map((finding) => finding.id).join(':')}`,
      affectedResourceCount: resourceKeys.size,
      kind,
      label,
      primaryFinding,
      relatedFindings: component.slice(1),
      findings: component,
    };
  });
}

/**
 * Keeps each group from the previous build whose findings are the same
 * objects in the same order. A group's fields derive only from its findings,
 * so the kept group is current, and rows keyed by group stay mounted when a
 * refresh changes other findings.
 */
export function reuseIdenticalPatrolFindingDisplayGroups<TFinding>(
  previous: readonly PatrolFindingDisplayGroup<TFinding>[],
  next: PatrolFindingDisplayGroup<TFinding>[],
): PatrolFindingDisplayGroup<TFinding>[] {
  const previousById = new Map(previous.map((group) => [group.id, group]));
  return next.map((group) => {
    const prior = previousById.get(group.id);
    return prior &&
      prior.findings.length === group.findings.length &&
      prior.findings.every((finding, index) => finding === group.findings[index])
      ? prior
      : group;
  });
}

export type PatrolFindingWorkType = 'approval' | 'failed' | 'in_progress' | 'recurring' | 'new';

const isFailedFixOutcome = (outcome: string | undefined): boolean =>
  outcome === 'fix_failed' ||
  outcome === 'fix_verification_failed' ||
  outcome === 'cannot_fix' ||
  outcome === 'timed_out';

export function classifyPatrolFindingWorkType(
  finding: Pick<
    UnifiedFinding,
    'status' | 'investigationStatus' | 'investigationOutcome' | 'regressionCount' | 'timesRaised'
  >,
): PatrolFindingWorkType {
  if (finding.status !== 'active') return 'new';

  if (finding.investigationOutcome === 'fix_queued') return 'approval';

  if (isFailedFixOutcome(finding.investigationOutcome)) return 'failed';

  if (
    finding.investigationStatus === 'running' ||
    finding.investigationOutcome === 'fix_executed'
  ) {
    return 'in_progress';
  }

  if ((finding.regressionCount ?? 0) > 0 || (finding.timesRaised ?? 0) > 1) {
    return 'recurring';
  }

  return 'new';
}

export interface PatrolWorkTypeComposition {
  total: number;
  approval: number;
  failed: number;
  inProgress: number;
  recurring: number;
  newIssues: number;
}

export function getPatrolWorkTypeComposition<
  TFinding extends Pick<
    UnifiedFinding,
    'status' | 'investigationStatus' | 'investigationOutcome' | 'regressionCount' | 'timesRaised'
  >,
>(findings: readonly TFinding[]): PatrolWorkTypeComposition {
  const composition: PatrolWorkTypeComposition = {
    total: findings.length,
    approval: 0,
    failed: 0,
    inProgress: 0,
    recurring: 0,
    newIssues: 0,
  };
  for (const finding of findings) {
    switch (classifyPatrolFindingWorkType(finding)) {
      case 'approval':
        composition.approval++;
        break;
      case 'failed':
        composition.failed++;
        break;
      case 'in_progress':
        composition.inProgress++;
        break;
      case 'recurring':
        composition.recurring++;
        break;
      case 'new':
        composition.newIssues++;
        break;
    }
  }
  return composition;
}

export function getPatrolWorkTypeCompositionClause(composition: PatrolWorkTypeComposition): string {
  const parts: string[] = [];
  if (composition.approval > 0) {
    parts.push(`${composition.approval} need${composition.approval === 1 ? 's' : ''} approval`);
  }
  if (composition.failed > 0) {
    parts.push(`${composition.failed} failed fix${composition.failed === 1 ? '' : 'es'}`);
  }
  if (composition.inProgress > 0) {
    parts.push(`${composition.inProgress} in progress`);
  }
  if (composition.recurring > 0) {
    parts.push(`${composition.recurring} recurring`);
  }
  if (parts.length === 0) return '';
  return ` — ${parts.join(', ')}`;
}

export interface PatrolActionableStatePresentation {
  label: string;
  tone: MetadataBadgeTone;
}

const formatBoundedFindingTime = (value: string): string | undefined => {
  if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(value))
    return undefined;
  const parsed = new Date(value);
  return Number.isNaN(parsed.valueOf()) ? undefined : parsed.toLocaleString();
};

export function getFindingEvidencePresentation(
  finding: Pick<UnifiedFinding, 'evidence' | 'key'>,
): string {
  const evidence = String(finding.evidence || '').trim();
  if (finding.key === 'apt-host-updates') {
    const match = evidence.match(
      /^pending_updates=(\d+) inventory=\S+ checked_at=(\S+) received_at=(\S+) reboot_required=(true|false)$/,
    );
    const count = match ? Number(match[1]) : Number.NaN;
    const checkedAt = match ? formatBoundedFindingTime(match[2]) : undefined;
    const receivedAt = match ? formatBoundedFindingTime(match[3]) : undefined;
    if (!match || !Number.isSafeInteger(count) || count < 0 || !checkedAt || !receivedAt)
      return 'Pulse could not safely present the bounded host-update observation. Refresh before acting.';
    const rebootBoundary =
      match[4] === 'true' ? 'Yes. No reboot is authorized by this finding or action.' : 'No.';
    return `${count} operating system update${count === 1 ? '' : 's'} ${count === 1 ? 'was' : 'were'} pending when the agent checked at ${checkedAt}. Pulse received that observation at ${receivedAt}. The host already reported reboot required: ${rebootBoundary}`;
  }
  if (finding.key === 'apt-package-cache-pressure') {
    const match = evidence.match(
      /^reclaimable_bytes=(\d+) filesystem_usage=([0-9.]+) fingerprint=\S+ checked_at=(\S+) received_at=(\S+)$/,
    );
    const bytes = match ? Number(match[1]) : Number.NaN;
    const usage = match ? Number(match[2]) : Number.NaN;
    const checkedAt = match ? formatBoundedFindingTime(match[3]) : undefined;
    const receivedAt = match ? formatBoundedFindingTime(match[4]) : undefined;
    if (
      !match ||
      !Number.isSafeInteger(bytes) ||
      bytes < 0 ||
      !Number.isFinite(usage) ||
      usage < 0 ||
      usage > 100 ||
      !checkedAt ||
      !receivedAt
    )
      return 'Pulse could not safely present the bounded package-cleanup observation. Refresh before acting.';
    return `${formatBytes(bytes)} of downloaded package data was reclaimable while the filesystem was ${usage}% full. The agent checked at ${checkedAt}, and Pulse received that observation at ${receivedAt}.`;
  }
  return evidence;
}

export function getPatrolFindingActionableState(
  finding: Pick<UnifiedFinding, 'status' | 'investigationStatus' | 'investigationOutcome'>,
): PatrolActionableStatePresentation | undefined {
  if (finding.status !== 'active') return undefined;

  if (finding.investigationOutcome === 'fix_queued') {
    return { label: 'Approval required', tone: 'warning' };
  }

  if (isFailedFixOutcome(finding.investigationOutcome)) {
    return { label: 'Fix failed', tone: 'danger' };
  }

  if (finding.investigationStatus === 'running') {
    return { label: 'Investigating', tone: 'info' };
  }

  if (finding.investigationOutcome === 'fix_executed') {
    return { label: 'Verifying fix', tone: 'info' };
  }

  // A restart cut the last run short. Patrol runs it again by itself, so the
  // row must not ask the operator to review anything.
  if (finding.investigationOutcome === 'interrupted') {
    return { label: 'Will retry', tone: 'neutral' };
  }

  return undefined;
}

export function getPatrolFindingQueueSummary(
  finding: Partial<Pick<UnifiedFinding, 'description' | 'impact' | 'recommendation'>>,
): string {
  for (const candidate of [finding.impact, finding.description, finding.recommendation]) {
    const normalized = String(candidate || '').trim();
    if (normalized) return normalized;
  }
  return 'Open this issue to review what Patrol found and decide the next step.';
}

export const getPatrolFindingIssueCountLabel = (count: number): string => {
  const normalized = Number.isFinite(count) ? Math.max(0, Math.trunc(count)) : 0;
  if (normalized === 1) {
    return '1 issue';
  }
  return `${normalized} issues`;
};

export const getFindingTitlePresentation = (
  finding: Pick<UnifiedFinding, 'resourceId' | 'resourceName' | 'title'>,
): FindingTitlePresentation => {
  const rawTitle = String(finding.title || '').trim();
  if (!isPatrolRuntimeFinding(finding)) {
    return { label: rawTitle };
  }

  const normalizedTitle = normalizePatrolRuntimeFindingLabel(rawTitle);
  return {
    label: normalizedTitle || rawTitle || 'Patrol runtime issue',
  };
};

export const getFindingPrimaryActionPresentation = (
  finding: Pick<UnifiedFinding, 'resourceId' | 'resourceName' | 'title'>,
): FindingPrimaryActionPresentation | undefined => {
  if (isPatrolRuntimeFinding(finding)) {
    return getPatrolProviderSettingsAction();
  }

  return undefined;
};

export const getFindingManualControlsPresentation = (
  finding: Pick<UnifiedFinding, 'resourceId' | 'resourceName' | 'title'>,
): FindingManualControlsPresentation =>
  isPatrolRuntimeFinding(finding)
    ? {
        acknowledge: false,
        snooze: false,
        dismiss: false,
      }
    : {
        acknowledge: true,
        snooze: true,
        dismiss: true,
      };

export const sortFindingsForAttentionQueue = (findings: UnifiedFinding[]): UnifiedFinding[] =>
  [...findings].sort((a, b) => {
    const aOutcome =
      a.status === 'active' && a.investigationOutcome
        ? getInvestigationOutcomeSortOrder(a.investigationOutcome)
        : 3;
    const bOutcome =
      b.status === 'active' && b.investigationOutcome
        ? getInvestigationOutcomeSortOrder(b.investigationOutcome)
        : 3;
    if (aOutcome !== bOutcome) return aOutcome - bOutcome;

    const aSeverity = getFindingSeveritySortOrder(a.severity);
    const bSeverity = getFindingSeveritySortOrder(b.severity);
    if (aSeverity !== bSeverity) return aSeverity - bSeverity;

    const aResourceCriticality = getFindingResourceCriticalitySortOrder(a.resourceCriticality);
    const bResourceCriticality = getFindingResourceCriticalitySortOrder(b.resourceCriticality);
    if (aResourceCriticality !== bResourceCriticality) {
      return aResourceCriticality - bResourceCriticality;
    }

    const aRuntime = getFindingActiveRuntimeSortOrder(a);
    const bRuntime = getFindingActiveRuntimeSortOrder(b);
    if (aRuntime !== bRuntime) return aRuntime - bRuntime;

    const aRecency = getFindingRecencyPresentation(a);
    const bRecency = getFindingRecencyPresentation(b);
    return new Date(bRecency.timestamp).getTime() - new Date(aRecency.timestamp).getTime();
  });

export const getFindingRecencyPresentation = (
  finding: Pick<UnifiedFinding, 'status' | 'detectedAt' | 'lastSeenAt'>,
): FindingRecencyPresentation => {
  if (finding.status === 'active' && finding.lastSeenAt) {
    return {
      label: 'last seen',
      timestamp: finding.lastSeenAt,
    };
  }

  return {
    label: 'detected',
    timestamp: finding.detectedAt,
  };
};

// A will_fix_later reminder and the end of a snooze are future times, so the
// row counts down to them ("Reminding in 6d") from the `now` the panel passes
// from the shared relative-time clock, and keeps the exact time on hover. A
// reminder reads overdue when `overdue` says the panel's overdue list holds it,
// the same list the Overdue commitments chip and filter count, so the three
// agree; read between the deadline and the clock tick that adds it there, it
// says "Reminder due". It stays overdue until the hourly reminder sweep brings
// the finding back, whether or not it still trips. A passed snooze has ended,
// so neither keeps counting.
export const getFindingReminderPresentation = (
  finding: Pick<UnifiedFinding, 'dismissedReason' | 'remindAt'>,
  now: number,
  overdue: boolean,
): FindingCountdownPresentation | null => {
  if (finding.dismissedReason !== 'will_fix_later' || !finding.remindAt) return null;
  const due = Date.parse(finding.remindAt);
  if (!Number.isFinite(due)) return null;
  const at = formatAbsoluteTime(due);
  if (overdue) {
    return {
      label: 'Reminder overdue',
      title: `Reminder was due ${at}. Pulse brings this finding back on its next reminder check.`,
    };
  }
  return {
    label:
      due <= now ? 'Reminder due' : `Reminding ${formatTimeUntil(due, { compact: true, now })}`,
    title: `Reminder due ${at}. Pulse brings this finding back on its first reminder check after that.`,
  };
};

export const getFindingSnoozePresentation = (
  finding: Pick<UnifiedFinding, 'status' | 'snoozedUntil'>,
  now: number,
): FindingCountdownPresentation | null => {
  if (finding.status !== 'snoozed' || !finding.snoozedUntil) return null;
  const until = Date.parse(finding.snoozedUntil);
  if (!Number.isFinite(until)) return null;
  const title = `Snoozed until ${formatAbsoluteTime(until)}`;
  if (until <= now) return { label: 'snooze ended', title };
  return { label: `snoozed, returns ${formatTimeUntil(until, { compact: true, now })}`, title };
};

export const getInvestigationStatusBadgeClasses = (status: InvestigationStatus): string =>
  INVESTIGATION_STATUS_CLASSES[status] || DEFAULT_BADGE_CLASSES;

export const getInvestigationStatusBadgeTone = (
  status: InvestigationStatus | string,
): MetadataBadgeTone =>
  INVESTIGATION_STATUS_TONES[status as InvestigationStatus] || DEFAULT_BADGE_TONE;

export const getInvestigationStatusLabel = (status: InvestigationStatus | string): string =>
  INVESTIGATION_STATUS_LABELS[status as InvestigationStatus] || String(status);

export const getInvestigationOutcomeBadgeClasses = (
  outcome: InvestigationOutcome | string,
): string =>
  INVESTIGATION_OUTCOME_CLASSES[outcome as InvestigationOutcome] || DEFAULT_BADGE_CLASSES;

export const getInvestigationOutcomeBadgeTone = (
  outcome: InvestigationOutcome | string,
): MetadataBadgeTone =>
  INVESTIGATION_OUTCOME_TONES[outcome as InvestigationOutcome] || DEFAULT_BADGE_TONE;

export const getInvestigationOutcomeLabel = (outcome: InvestigationOutcome | string): string =>
  INVESTIGATION_OUTCOME_LABELS[outcome as InvestigationOutcome] || String(outcome);

// Confidence badge classes mirror severity intuition: high is reassuringly
// emphasized, medium is neutral, low is a soft amber so the operator notices
// when the trust signal is weak.
const INVESTIGATION_CONFIDENCE_CLASSES: Record<string, string> = {
  high: 'border-emerald-300 bg-emerald-50 text-emerald-800 dark:border-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300',
  medium: 'border-border bg-surface-alt text-base-content',
  low: 'border-amber-300 bg-amber-50 text-amber-800 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-300',
};

const INVESTIGATION_CONFIDENCE_TONES: Record<string, MetadataBadgeTone> = {
  high: 'success',
  medium: 'neutral',
  low: 'warning',
};

export const getInvestigationConfidenceBadgeClasses = (confidence: string): string =>
  INVESTIGATION_CONFIDENCE_CLASSES[confidence] || DEFAULT_BADGE_CLASSES;

export const getInvestigationConfidenceBadgeTone = (confidence: string): MetadataBadgeTone =>
  INVESTIGATION_CONFIDENCE_TONES[confidence] || DEFAULT_BADGE_TONE;

export const getInvestigationOutcomeSortOrder = (
  outcome: InvestigationOutcome | string | undefined,
): number => {
  if (!outcome) {
    return 3;
  }
  return INVESTIGATION_OUTCOME_SORT_ORDER[outcome] ?? 3;
};

export const hasFindingInvestigationDetails = (
  finding: Pick<
    UnifiedFinding,
    | 'investigationSessionId'
    | 'investigationStatus'
    | 'investigationOutcome'
    | 'investigationAttempts'
  >,
): boolean =>
  Boolean(
    finding.investigationSessionId?.trim() ||
    finding.investigationStatus ||
    finding.investigationOutcome ||
    (finding.investigationAttempts ?? 0) > 0,
  );

const ATTENTION_OUTCOMES = new Set([
  'fix_verification_failed',
  'fix_verification_unknown',
  'fix_failed',
  'fix_rejected',
  'timed_out',
  'needs_attention',
  'cannot_fix',
  'unclassified',
]);

export const hasPendingInvestigationFixApproval = (
  findingId: string,
  approvals: Pick<ApprovalRequest, 'status' | 'toolId' | 'targetId' | 'expiresAt'>[],
  now = Date.now(),
): boolean =>
  approvals.some(
    (approval) =>
      isLivePendingApproval(approval, now) &&
      approval.toolId === 'investigation_fix' &&
      approval.targetId === findingId,
  );

export const isPatrolInvestigationFixApproval = (
  approval: Pick<ApprovalRequest, 'toolId'>,
): boolean => approval.toolId === 'investigation_fix';

export const doesFindingNeedAttention = (
  finding: Pick<UnifiedFinding, 'id' | 'status' | 'investigationOutcome' | 'investigationRecord'>,
  approvals: Pick<ApprovalRequest, 'status' | 'toolId' | 'targetId' | 'expiresAt'>[] = [],
): boolean => {
  if (finding.status !== 'active' || !finding.investigationOutcome) {
    return false;
  }

  if (ATTENTION_OUTCOMES.has(finding.investigationOutcome)) {
    return true;
  }

  return (
    finding.investigationOutcome === 'fix_queued' &&
    !hasPendingInvestigationFixApproval(finding.id, approvals) &&
    !finding.investigationRecord?.action
  );
};

export const getFindingPatrolWorkflowPresentation = (
  finding: Pick<
    UnifiedFinding,
    | 'id'
    | 'source'
    | 'status'
    | 'resourceId'
    | 'resourceName'
    | 'title'
    | 'investigationStatus'
    | 'investigationOutcome'
    | 'investigationRecord'
    | 'loopState'
  >,
  approvals: Pick<ApprovalRequest, 'status' | 'toolId' | 'targetId' | 'expiresAt'>[] = [],
  now = Date.now(),
): FindingPatrolWorkflowPresentation | undefined => {
  if (finding.source !== 'ai-patrol') {
    return undefined;
  }

  if (finding.status === 'resolved') {
    return {
      stage: 'recorded',
      label: 'Outcome recorded',
      detail: 'Patrol has a verified or cleared outcome for this finding.',
      tone: 'success',
    };
  }

  if (finding.status === 'snoozed') {
    return {
      stage: 'paused',
      label: 'Paused until reminder',
      detail: 'Patrol will surface this again when the snooze expires.',
      tone: 'info',
    };
  }

  if (finding.status !== 'active') {
    return undefined;
  }

  if (isPatrolRuntimeFinding(finding)) {
    return {
      stage: 'attention',
      label: 'Fix Patrol setup',
      detail: 'Patrol needs runtime or provider setup before it can check infrastructure reliably.',
      tone: 'info',
    };
  }

  const typedActionState = finding.investigationRecord?.action?.state;
  if (typedActionState === 'pending_approval') {
    return {
      stage: 'approval',
      label: 'Approve or reject',
      detail: 'A typed governed action is waiting for an operator decision.',
      tone: 'warning',
    };
  }
  if (typedActionState === 'planned') {
    return {
      stage: 'approval',
      label: 'Run action',
      detail: 'The typed action plan is ready to run under its declared policy.',
      tone: 'info',
    };
  }
  if (typedActionState === 'approved') {
    return {
      stage: 'approval',
      label: 'Run approved action',
      detail: 'The typed action is approved. Execution remains a separate operator step.',
      tone: 'success',
    };
  }
  if (typedActionState === 'executing') {
    return {
      stage: 'verification',
      label: 'Action running',
      detail: 'The governed action is running and will publish its verification result.',
      tone: 'info',
    };
  }

  const hasLiveApproval = hasPendingInvestigationFixApproval(finding.id, approvals, now);
  if (hasLiveApproval) {
    return {
      stage: 'approval',
      label: 'Approve or reject',
      detail: 'A governed fix is waiting for an approve or reject decision.',
      tone: 'warning',
    };
  }

  if (
    finding.investigationStatus === 'running' ||
    finding.investigationStatus === 'pending' ||
    finding.loopState === 'investigating'
  ) {
    return {
      stage: 'investigating',
      label: 'Patrol investigating',
      detail: 'Patrol is gathering context before asking for a decision.',
      tone: 'indigo',
    };
  }

  switch (finding.investigationOutcome) {
    case 'resolved':
    case 'fix_verified':
      return {
        stage: 'recorded',
        label: 'Outcome recorded',
        detail: 'Patrol verified or cleared this finding.',
        tone: 'success',
      };
    case 'fix_queued':
      return {
        stage: 'approval',
        label: 'Recover action',
        detail:
          'An older queued outcome has no canonical action reference. Expand the finding to review recovery options.',
        tone: 'warning',
      };
    case 'fix_executed':
      return {
        stage: 'verification',
        label: 'Verify outcome',
        detail: 'Patrol executed a governed fix and is waiting for verification.',
        tone: 'info',
      };
    case 'fix_failed':
    case 'fix_verification_failed':
      return {
        stage: 'attention',
        label: 'Fix failed',
        detail:
          'The governed action did not resolve the finding. Reopen context before trying another change.',
        tone: 'danger',
      };
    case 'fix_rejected':
      return {
        stage: 'attention',
        label: 'Decide follow-up',
        detail:
          'The last governed fix was rejected. Review the finding for another option or mark it resolved after manual work.',
        tone: 'warning',
      };
    case 'fix_verification_unknown':
      return {
        stage: 'verification',
        label: 'Check outcome',
        detail: 'Patrol could not verify the fix. Inspect the resource or gather more evidence.',
        tone: 'warning',
      };
    case 'needs_attention':
    case 'cannot_fix':
    case 'timed_out':
      return {
        stage: 'attention',
        label: 'Needs input',
        detail: 'Patrol needs operator context before continuing.',
        tone: 'warning',
      };
    case 'unclassified':
      return {
        stage: 'attention',
        label: 'Read summary',
        detail:
          'Patrol finished without a clear conclusion. Read its summary. Patrol looks again on a later run.',
        tone: 'warning',
      };
    case 'interrupted':
      return {
        stage: 'investigating',
        label: 'Will retry',
        detail:
          'The last run was cut short, usually by a Pulse restart. Patrol runs it again on its next pass.',
        tone: 'neutral',
      };
    default:
      return undefined;
  }
};

export const getFindingLoopStateBadgeClasses = (loopState: string): string =>
  FINDING_LOOP_STATE_CLASSES[loopState] || DEFAULT_LOOP_STATE_CLASSES;

export const getFindingLoopStateBadgeTone = (loopState: string): MetadataBadgeTone =>
  FINDING_LOOP_STATE_TONES[loopState] || DEFAULT_BADGE_TONE;

export const formatFindingLoopState = (loopState: string): string =>
  formatIdentifierLabel(loopState);

export const formatFindingLifecycleType = (value: string): string =>
  FINDING_LIFECYCLE_LABELS[value] || formatIdentifierLabel(value);

export const getFindingResolutionReason = (
  finding: Pick<
    UnifiedFinding,
    'isThreshold' | 'source' | 'alertType' | 'investigationOutcome' | 'autoResolved'
  >,
  resolvedTime: string,
): string => {
  // Operator-driven manual resolution takes priority over the
  // category-specific copy: "Resolved by you" tells the operator (and any
  // teammate revisiting the timeline) that this closure was their action,
  // not Pulse's auto-detection. Patrol auto-resolution paths (fix_verified,
  // fix_executed) keep their existing copy because they describe Pulse's own
  // remediation outcome, which is more specific than "auto-resolved by Pulse".
  if (
    finding.autoResolved === false &&
    finding.investigationOutcome !== 'fix_verified' &&
    finding.investigationOutcome !== 'fix_executed' &&
    finding.investigationOutcome !== 'resolved'
  ) {
    return `Resolved by you ${resolvedTime}`;
  }
  if (finding.isThreshold || finding.source === 'threshold') {
    switch (finding.alertType || '') {
      case 'powered-off':
        return `Guest came online ${resolvedTime}`;
      case 'host-offline':
        return `Agent came online ${resolvedTime}`;
      case 'cpu':
        return `CPU returned to normal ${resolvedTime}`;
      case 'memory':
        return `Memory returned to normal ${resolvedTime}`;
      case 'disk':
        return `Disk usage returned to normal ${resolvedTime}`;
      case 'network':
        return `Network recovered ${resolvedTime}`;
      default:
        return `Condition cleared ${resolvedTime}`;
    }
  }

  if (finding.source === 'ai-patrol') {
    switch (finding.investigationOutcome) {
      case 'fix_verified':
        return `Fixed by Patrol ${resolvedTime}`;
      case 'fix_executed':
        return `Fix applied by Patrol ${resolvedTime}`;
      case 'resolved':
        return `Resolved by Patrol ${resolvedTime}`;
      case 'fix_failed':
        return `Resolved after fix failed ${resolvedTime}`;
      case 'fix_rejected':
        return `Resolved after rejected fix ${resolvedTime}`;
      case 'fix_queued':
        return `Resolved while fix was pending ${resolvedTime}`;
      case 'fix_verification_failed':
        return `Resolved after failed verification ${resolvedTime}`;
      case 'fix_verification_unknown':
        return `Resolved after inconclusive verification ${resolvedTime}`;
      case 'timed_out':
        return `Resolved after investigation timeout ${resolvedTime}`;
      case 'cannot_fix':
      case 'needs_attention':
      case 'unclassified':
      case 'interrupted':
        // An investigation outcome does not identify who later resolved the
        // finding. Explicit operator resolution is handled above.
        return `Resolved ${resolvedTime}`;
      default:
        return `Issue no longer detected ${resolvedTime}`;
    }
  }

  return `Resolved ${resolvedTime}`;
};

export const buildFindingFilterOptions = (counts: {
  needsAttentionCount: number;
  pendingApprovalCount: number;
}): FindingFilterOption[] => {
  const options: FindingFilterOption[] = [
    { value: 'active', label: 'Active' },
    { value: 'all', label: 'All' },
    { value: 'resolved', label: 'Resolved' },
  ];

  if (counts.needsAttentionCount > 0) {
    options.push({
      value: 'attention',
      label: 'Needs Attention',
      tone: 'warning',
      count: counts.needsAttentionCount,
    });
  }

  if (counts.pendingApprovalCount > 0) {
    options.push({
      value: 'approvals',
      label: 'Approvals',
      tone: 'warning',
      count: counts.pendingApprovalCount,
    });
  }

  return options;
};

export const getFindingEmptyStateCopy = (filter: FindingsFilter): FindingEmptyStateCopy => {
  switch (filter) {
    case 'active':
      return {
        title: 'No active findings',
        body: 'Your infrastructure looks healthy!',
      };
    case 'attention':
      return {
        title: 'No findings need attention right now.',
      };
    case 'approvals':
      return {
        title: 'No pending approvals.',
      };
    default:
      return {
        title: 'No Patrol findings to display',
      };
  }
};

/**
 * Format a finding as a Markdown summary the operator can paste into a chat
 * message, ticket, or incident channel. The output mirrors the seven-question
 * schema in render order — title + resource header, then description, impact,
 * recommendation, plus the trust signals (confidence, regression count) that
 * matter most to a teammate seeing the finding cold.
 *
 * Intentionally lean: only fields the operator can paste verbatim, no internal
 * IDs or timestamps in epoch form. Investigation evidence and rollback plans
 * are deferred to the Discuss with Assistant flow because those are
 * conversation context, not "share this finding" context.
 */
export const formatFindingForClipboard = (
  finding: Pick<
    UnifiedFinding,
    | 'severity'
    | 'title'
    | 'resourceName'
    | 'resourceType'
    | 'description'
    | 'impact'
    | 'recommendation'
    | 'investigationRecord'
    | 'regressionCount'
  >,
): string => {
  const lines: string[] = [];
  const severity = finding.severity ? finding.severity.toUpperCase() : 'FINDING';
  const resource = [finding.resourceName, finding.resourceType ? `(${finding.resourceType})` : '']
    .filter(Boolean)
    .join(' ')
    .trim();
  lines.push(`**[${severity}] ${finding.title || 'Untitled finding'}**`);
  if (resource) {
    lines.push(`Resource: ${resource}`);
  }
  if (finding.description) {
    lines.push('');
    lines.push(`Description: ${finding.description}`);
  }
  if (finding.impact) {
    lines.push('');
    lines.push(`Impact: ${finding.impact}`);
  }
  const trustParts: string[] = [];
  const confidence = finding.investigationRecord?.confidence;
  if (confidence) {
    trustParts.push(`Confidence: ${confidence}`);
  }
  if ((finding.regressionCount || 0) > 0) {
    trustParts.push(`Regressed: ${finding.regressionCount}×`);
  }
  if (trustParts.length > 0) {
    lines.push('');
    lines.push(trustParts.join(' · '));
  }
  return lines.join('\n');
};

/**
 * Returns the canonical `operator_state_cause` for a finding's most
 * recent dismissed lifecycle event, or "" when the finding has not been
 * auto-dismissed by operator-state suppression. Scans newest-first and
 * stops at the first `dismissed` event so a manual operator dismissal
 * that supersedes an earlier auto-dismiss is reported as manual (no
 * stale cause leaks through). Mirrors the Go-side
 * `findOperatorStateDismissCause` helper from
 * `internal/ai/findings.go`.
 *
 * Used by render code to badge auto-dismissed findings differently
 * from manual operator dismissals — both show DismissedReason=
 * 'expected_behavior' on the wire but tell different stories: Pulse
 * auto-handled vs operator decided.
 */
export const getOperatorStateDismissCause = (
  finding: Pick<UnifiedFinding, 'lifecycle'>,
): string => {
  const lifecycle = finding.lifecycle;
  if (!lifecycle || lifecycle.length === 0) return '';
  for (let i = lifecycle.length - 1; i >= 0; i -= 1) {
    const ev = lifecycle[i];
    if (ev.type !== 'dismissed') continue;
    const cause = ev.metadata?.operator_state_cause;
    if (cause) return cause;
    // First dismissed event without cause is a manual dismissal that
    // supersedes any earlier auto-dismiss — stop scanning so a stale
    // earlier cause does not falsely badge the finding as
    // auto-suppressed.
    return '';
  }
  return '';
};

/**
 * Human-readable label for an `operator_state_cause` value. Returns
 * empty string for unknown values so render code can gate cleanly.
 */
export const formatOperatorStateDismissCauseLabel = (cause: string): string => {
  switch (cause) {
    case 'maintenance_window':
      return 'maintenance';
    case 'intentionally_offline':
      return 'intentionally offline';
    default:
      return '';
  }
};