// Copyright (c) 2026 Hellmai Ltd
// SPDX-License-Identifier: AGPL-3.0-only

import { createError, ErrorCodes } from '@lumenflow/kernel/primitives/error-handler';

/**
 * WU-2765: authoritative ADR-014 memory coordination field names.
 *
 * These axes are shared by mem:signal persistence and mem:context roster
 * rendering, so they live with the agent-runtime pack rather than memory core.
 */
export const MEMORY_COORDINATION_SIGNAL_FIELD_NAMES = [
  'role',
  'target_role',
  'initiative',
  'delegation_id',
] as const;

export type MemoryCoordinationFieldName = (typeof MEMORY_COORDINATION_SIGNAL_FIELD_NAMES)[number];

export interface MemoryCoordinationSignalFields {
  role?: string;
  target_role?: string;
  initiative?: string;
  delegation_id?: string;
}

export function isNonEmptyCoordinationFieldValue(value: unknown): value is string {
  return typeof value === 'string' && value.trim().length > 0;
}

export function normalizeCoordinationField(
  value: string | undefined,
  fieldName: MemoryCoordinationFieldName,
): string | undefined {
  if (value === undefined) {
    return undefined;
  }

  const normalized = value.trim();
  if (normalized.length === 0) {
    throw createError(
      ErrorCodes.VALIDATION_ERROR,
      `Signal metadata fields must be non-empty strings when provided: ${fieldName}`,
    );
  }

  return normalized;
}

/**
 * WU-2755/WU-2765: compact signal summary attached to a roster row.
 */
export interface CoordinationRosterSignalSummary {
  id: string;
  message: string;
  role?: string;
  target_role?: string;
  created_at: string;
}

/**
 * WU-2755/WU-2765: one active delegation/session roster row.
 */
export interface CoordinationRosterEntry {
  delegation_id: string;
  target_wu_id: string;
  lane?: string;
  requested_role?: string;
  actual_role?: string;
  display_name?: string;
  lifecycle_role?: string;
  specialty_profile?: string;
  current_wu?: string;
  last_heartbeat?: string;
  ownership_scope?: string;
  status?: string;
  recent_signals?: CoordinationRosterSignalSummary[];
}

/**
 * WU-2755/WU-2765: caller-composed coordination roster input for mem:context.
 */
export interface CoordinationRoster {
  entries: CoordinationRosterEntry[];
}
