/**
 * Pure construction of the first-run/edit wizard rows (ticket #44).
 *
 * The wizard runs in one of two **modes**, passed explicitly (never inferred
 * from `isFirstRun`):
 *
 *  - `"firstRun"` — the very first launch. Rows come from the selectable
 *    reference catalogue only, all unselected, availability unknown. Detection
 *    later pre-checks the installed CLIs.
 *  - `"edit"` — reopened via *Settings ▸ Configure profiles*. The user already
 *    configured profiles (possibly several local OpenCode ones with distinct
 *    endpoints); those must come back **pre-selected with their real config**, so
 *    a save doesn't silently drop them. Reference profiles are still offered, but
 *    only those not already configured — deduplicated **by `id` only**.
 *
 * Deduplication is by `profile.id` and nothing else: several OpenCode profiles
 * legitimately share the same `command`/`structuredAdapter` while differing in
 * endpoint/model, so their product identity is the id. A reference is "already
 * configured" iff a configured profile carries the same id.
 */

import type { AgentProfile } from "@/domain";

/** Which wizard the rows are being built for (ticket #44). */
export type WizardMode = "firstRun" | "edit";

/** One row in the wizard: a candidate profile, selected state, availability. */
export interface WizardEntry {
  profile: AgentProfile;
  selected: boolean;
  /** `null` until detection ran; then `true`/`false`. */
  available: boolean | null;
}

/**
 * Builds the wizard rows for the given mode. Pure — no I/O, no React — so every
 * invariant (pre-selection, id-only dedup, ordering) is unit-testable.
 *
 * `firstRun`: references only, all `selected:false`, `available:null`.
 * `edit`: the configured profiles first (pre-selected, real config intact), then
 * the reference profiles whose id is not already configured (`selected:false`).
 */
export function buildWizardEntries({
  mode,
  configured,
  references,
}: {
  mode: WizardMode;
  configured: AgentProfile[];
  references: AgentProfile[];
}): WizardEntry[] {
  if (mode === "firstRun") {
    return references.map((profile) => ({
      profile,
      selected: false,
      available: null,
    }));
  }

  // Edit mode: configured profiles come first, pre-selected and untouched.
  const configuredIds = new Set(configured.map((p) => p.id));
  const configuredEntries: WizardEntry[] = configured.map((profile) => ({
    profile,
    selected: true,
    available: null,
  }));
  // Then the references not already configured — matched by id ONLY.
  const referenceEntries: WizardEntry[] = references
    .filter((p) => !configuredIds.has(p.id))
    .map((profile) => ({ profile, selected: false, available: null }));

  return [...configuredEntries, ...referenceEntries];
}
