/**
 * Host capability declaration — platform-agnostic (WP-01).
 * Capability must be declared by adapters; Core never guesses by name.
 */

export type HostCapabilityLevel = "H0" | "H1" | "H2" | "H3";

export interface HostCapabilities {
  level: HostCapabilityLevel;
  persistentSession: boolean;
  resumableSession: boolean;
  structuredEvents: boolean;
  cancellableRun: boolean;
  inspectableSession: boolean;
  workspaceBinding: boolean;
  concurrentWorkers: boolean;
  /** Open extension bag — unknown keys must not break consumers. */
  extensions?: Record<string, unknown>;
}

/**
 * Normalize capabilities for tolerant readers. Unknown extension keys are kept.
 */
export function normalizeHostCapabilities(
  input: Partial<HostCapabilities> & Record<string, unknown>,
): HostCapabilities {
  const level = (input.level as HostCapabilityLevel | undefined) ?? "H0";
  const {
    persistentSession,
    resumableSession,
    structuredEvents,
    cancellableRun,
    inspectableSession,
    workspaceBinding,
    concurrentWorkers,
    extensions,
    ...rest
  } = input;
  const knownExt = extensions && typeof extensions === "object" ? { ...extensions } : {};
  for (const [k, v] of Object.entries(rest)) {
    if (
      ![
        "level",
        "persistentSession",
        "resumableSession",
        "structuredEvents",
        "cancellableRun",
        "inspectableSession",
        "workspaceBinding",
        "concurrentWorkers",
        "extensions",
      ].includes(k)
    ) {
      knownExt[k] = v;
    }
  }
  return {
    level,
    persistentSession: Boolean(persistentSession),
    resumableSession: Boolean(resumableSession),
    structuredEvents: Boolean(structuredEvents),
    cancellableRun: Boolean(cancellableRun),
    inspectableSession: Boolean(inspectableSession),
    workspaceBinding: Boolean(workspaceBinding),
    concurrentWorkers: Boolean(concurrentWorkers),
    ...(Object.keys(knownExt).length > 0 ? { extensions: knownExt } : {}),
  };
}
