/**
 * MXESC-1: Bijective String Encoding for Wire Topics
 *
 * Per MATRIX-PROTOCOL-2 §8.3.1:
 * - Safe set: [A-Za-z0-9._~-/]  (slashes allowed for topic hierarchy)
 * - All other characters: %HH percent-encoding (uppercase hex)
 *
 * CRITICAL: This encoding is BIJECTIVE - decode(encode(x)) === x for all x.
 * This is required by Protocol Invariant #4 (MATRIX-PROTOCOL-3 §25).
 */

export function mxesc1Encode(input: string): string {
  const bytes = new TextEncoder().encode(input);
  let result = '';

  for (const byte of bytes) {
    const char = String.fromCharCode(byte);
    if (/[A-Za-z0-9._~\-/]/.test(char)) {
      result += char;
    } else {
      result += '%' + byte.toString(16).toUpperCase().padStart(2, '0');
    }
  }

  return result;
}

export function mxesc1Decode(encoded: string): string {
  const bytes: number[] = [];

  for (let i = 0; i < encoded.length; i++) {
    if (encoded[i] === '%' && i + 2 < encoded.length) {
      const hex = encoded.slice(i + 1, i + 3);
      const byte = parseInt(hex, 16);
      if (!isNaN(byte)) {
        bytes.push(byte);
        i += 2;
        continue;
      }
    }
    bytes.push(encoded.charCodeAt(i));
  }

  return new TextDecoder().decode(new Uint8Array(bytes));
}
