/**
 * The chat URL vocabulary — one place, so a link built in a panel and a link built on the server
 * cannot drift apart.
 *
 * A project group is a working directory, and a working directory is an absolute path, so it goes in
 * the URL *as* a path: `/chat/g/home/me/project`. The leading slash is implied — every cwd is absolute
 * — and that is what keeps the URL free of `%2F`, which proxies normalise or reject and Officer always
 * sits behind one. It stays readable and copy-pasteable, which a percent-encoded blob or a lossy slug
 * would not.
 *
 * **A session is not addressed by group.** Its transcript records its own cwd and the server resolves
 * it from the id alone, so `/chat/<id>` is already complete. Carrying the group as well would be a
 * second copy of a fact the id determines — and a second copy is free to disagree, which is exactly
 * how a resumed session used to get launched in the wrong directory.
 */

/** Discriminator segment, so a group path can never be mistaken for a session id. */
export const GROUP_SEGMENT = 'g';

/** Absolute cwd → path suffix. Encoded per segment; React Router decodes it the same way. */
const encodeCwd = (cwd: string): string => cwd.split('/').filter(Boolean).map(encodeURIComponent).join('/');

/** The list for a group. `null` = the caller's own home. */
export const chatListPath = (cwd: string | null | undefined): string =>
  cwd ? `/chat/${GROUP_SEGMENT}/${encodeCwd(cwd)}` : '/chat';

/** A new chat in a group. `null` = the default group. */
export const chatNewPath = (cwd: string | null | undefined): string =>
  cwd ? `/chat/new/${GROUP_SEGMENT}/${encodeCwd(cwd)}` : '/chat/new';

/** A conversation. Deliberately group-free — see the note above. */
export const chatSessionPath = (sessionId: string): string => `/chat/${sessionId}`;

/**
 * Route splat → absolute cwd. React Router hands the splat back already decoded (per segment, with any
 * decoded `/` re-escaped), so this only has to put the leading slash back. An empty splat — `/chat/g`
 * with nothing after it — means the default group rather than the filesystem root.
 */
export const cwdFromSplat = (splat: string | undefined): string | null => {
  const trimmed = splat?.replace(/^\/+|\/+$/g, '');
  return trimmed ? `/${trimmed}` : null;
};
