/** Path prefix Studio apps are served under on the app host: `/studio/<app>`. */
export const Z2H_APP_ROUTE_PREFIX = '/studio';

/**
 * Former prefix (`/bigbrain-vibe/<app>`). bigbrain-host redirects it to
 * {@link Z2H_APP_ROUTE_PREFIX}, but anything that parses app URLs must keep
 * recognising it: old links live on in Slack, bookmarks and older z2h-cli builds.
 */
export const Z2H_LEGACY_APP_ROUTE_PREFIX = '/bigbrain-vibe';

/** Every prefix a Studio app URL may use, current first. */
export const Z2H_APP_ROUTE_PREFIXES = [Z2H_APP_ROUTE_PREFIX, Z2H_LEGACY_APP_ROUTE_PREFIX] as const;

/** The parts of a Studio app path, e.g. `/embed/x/studio/my-app/reports/7`. */
export interface Z2hAppRoute {
  /** Where the prefix starts: 0 unless the host is mounted under a sub-path (`/embed/x`). */
  start: number;
  /** Everything up to and including the slug: `/embed/x/studio/my-app`. */
  base: string;
  /** `my-app`. Empty for a bare `/studio/`. Not validated. */
  slug: string;
  /** The app's own path after the slug, always starting with `/`: `/reports/7`, or `/`. */
  rest: string;
}

/**
 * Finds the Studio app route in a path, under either prefix and wherever it sits
 * (the earliest match wins), or `null` when the path has none. A prefix only
 * counts as a whole segment: `/studio-home/x` is not a Studio app path.
 */
export function findZ2hAppRoute(pathname: string): Z2hAppRoute | null {
  let start = -1;
  let prefix = '';
  for (const p of Z2H_APP_ROUTE_PREFIXES) {
    const idx = pathname.indexOf(`${p}/`);
    if (idx >= 0 && (start < 0 || idx < start)) {
      start = idx;
      prefix = p;
    }
  }
  if (start < 0) {
    return null;
  }

  const slugStart = start + prefix.length + 1;
  const slugEnd = pathname.indexOf('/', slugStart);
  const end = slugEnd >= 0 ? slugEnd : pathname.length;
  return {
    start,
    base: pathname.slice(0, end),
    slug: pathname.slice(slugStart, end),
    rest: slugEnd >= 0 ? pathname.slice(slugEnd) : '/',
  };
}

/** The app slug from a Studio app path, or `null`: `/studio/my-app/sub` → `my-app`. */
export function z2hAppSlugFromPath(pathname: string): string | null {
  return findZ2hAppRoute(pathname)?.slug || null;
}
