/**
 * What a panel is mounted on, parsed once by the framework instead of by each app that cares.
 *
 * The framework persists a workspace under a dashboard-state key: `ws-layout-<id>` for a user-created
 * dashboard, `screens/<name>` for one of the fixed screens. That key used to be handed to apps raw, as
 * `dashboardId`, and three of them reverse-engineered meaning out of its shape — a regex here, a
 * `startsWith('screens/')` there, an equality test against a literal somewhere else. Two consequences,
 * both real: a key that failed one parser and passed another produced `ws-host-terminals-ws-layout-my-dash`,
 * which the server obligingly created as a dashboard; and the agent address book is keyed on this string,
 * so a change to how the key is derived orphans every named agent on the dashboard — rows and sessions
 * alive, panels unable to find them.
 *
 * So: parse in one place, and keep `key` on the result. Storage keys are addresses that outlive the
 * session, and the parsed halves are for deciding, never for writing.
 */
export type WorkspaceIdentity = {
  /** `dashboard` is user-created and can host named agents; `screen` is a fixed route like `screens/email`. */
  kind: 'dashboard' | 'screen';
  /** The bare id — `agent-mvp` for `ws-layout-agent-mvp`, `email` for `screens/email`. For deciding. */
  id: string;
  /** The dashboard-state key this workspace persists under, and `agent_panels.dashboard_id`. For storing. */
  key: string;
};

/**
 * Null for anything that is not one of the two known shapes — including a workspace that has no key at
 * all (a preview, a settings pane). Callers should read that as "not a dashboard and not a screen", which
 * is what it is; the previous `!key.startsWith('screens/')` test called an unrecognised key a dashboard
 * and would have let a panel try to register an agent against it.
 */
export function parseWorkspaceKey(key: string | null | undefined): WorkspaceIdentity | null {
  if (!key) return null;

  const dashboard = /^ws-layout-(.+)$/.exec(key);
  if (dashboard) return { kind: 'dashboard', id: dashboard[1]!, key };

  const screen = /^screens\/(.+)$/.exec(key);
  if (screen) return { kind: 'screen', id: screen[1]!, key };

  return null;
}
