/**
 * Root Identity Parsing
 *
 * Parses root strings into structured identity objects.
 * Distinguishes between root groups (e.g., "flowpad") and
 * root instances (e.g., "flowpad.tab-abc123").
 */

import { RootId } from './identity';

export interface RootGroup {
  kind: 'group';
  value: string;
  group: RootId;
}

export interface RootInstance {
  kind: 'instance';
  value: string;
  group: RootId;
  instance: string;
}

export type RootIdentity = RootGroup | RootInstance;

// Deprecated aliases
/** @deprecated Use RootGroup */
export type RealmGroup = RootGroup;
/** @deprecated Use RootInstance */
export type RealmInstance = RootInstance;
/** @deprecated Use RootIdentity */
export type RealmIdentity = RootIdentity;

/**
 * Parse a root string into a structured identity.
 *
 * - "flowpad" -> RootGroup { group: "flowpad" }
 * - "flowpad.tab-abc123" -> RootInstance { group: "flowpad", instance: "abc123" }
 */
export function parseRootIdentity(root: string): RootIdentity {
  const tabMatch = root.match(/^(.+)\.tab-([a-z0-9]+)$/);
  if (tabMatch) {
    return {
      kind: 'instance',
      value: root,
      group: RootId.of(tabMatch[1]),
      instance: tabMatch[2],
    };
  }
  return {
    kind: 'group',
    value: root,
    group: RootId.of(root),
  };
}

/** @deprecated Use parseRootIdentity instead */
export const parseRealmIdentity = parseRootIdentity;

/**
 * Check if a root identity is an instance (has .tab-xxx suffix).
 */
export function isRootInstance(identity: RootIdentity): identity is RootInstance {
  return identity.kind === 'instance';
}

/** @deprecated Use isRootInstance instead */
export const isRealmInstance = isRootInstance;

/**
 * Get the group root from any root identity.
 */
export function getRootGroup(identity: RootIdentity): RootId {
  return identity.group;
}

/** @deprecated Use getRootGroup instead */
export const getRealmGroup = getRootGroup;
