"""Original bounded suffix-index/LCP discovery. No source code copied."""
from itertools import product
import json

def lrs(text):
 if type(text) is not str or len(text)>16:raise ValueError('literal Unicode text length0..16')
 sa=sorted(range(len(text)),key=lambda i:text[i:]);rows=[];best=''
 for left,right in zip(sa,sa[1:]):
  n=0
  while left+n<len(text) and right+n<len(text) and text[left+n]==text[right+n]:n+=1
  candidate=text[left:left+n];rows.append({'left_suffix_start':left,'right_suffix_start':right,'lcp':n,'prefix':candidate})
  if len(candidate)>len(best) or (len(candidate)==len(best) and candidate<best):best=candidate
 places=[i for i in range(len(text)-len(best)+1) if best and text[i:i+len(best)]==best]
 return {'text':text,'sorted_suffix_indices':sa,'suffixes':[text[i:] for i in sa],'adjacent_lcp':rows,'longest_repeated_substring':best,'length':len(best),'all_occurrence_starts':places}

def oracle(text):
 occurrences={}
 for i in range(len(text)):
  for j in range(i+1,len(text)+1):occurrences.setdefault(text[i:j],[]).append(i)
 choices=[s for s,indices in occurrences.items() if len(indices)>1]
 best=min(choices,key=lambda s:(-len(s),s)) if choices else ''
 return best,occurrences.get(best,[])

def demo():
 fixtures=[]
 for text in ['banana','aaaa','کارکار','ababcdcd','a a a','', 'a','abcdef']:
  out=lrs(text);best,places=oracle(text);assert (out['longest_repeated_substring'],out['all_occurrence_starts'])==(best,places);fixtures.append(out)
 assert fixtures[0]['longest_repeated_substring']=='ana' and fixtures[0]['all_occurrence_starts']==[1,3]
 assert fixtures[1]['longest_repeated_substring']=='aaa' and fixtures[1]['all_occurrence_starts']==[0,1]
 checks=0
 for n in range(8):
  for chars in product('ab',repeat=n):
   text=''.join(chars);out=lrs(text);best,places=oracle(text);assert (out['longest_repeated_substring'],out['all_occurrence_starts'])==(best,places);checks+=1
 rejected=[]
 for bad in [True,None,'x'*17]:
  try:lrs(bad)
  except ValueError:rejected.append(repr(bad))
  else:raise AssertionError('expected rejection')
 return {'authored_examples':fixtures,'all_binary_strings_length0_to7_oracles':checks,'invalid_inputs_rejected':rejected,'contract':'overlap allowed, tie longest then lexicographically smallest codepoint substring, all distinct starting positions; no whitespace normalization, byte/grapheme indexing or semantic similarity','complexity':'bounded teaching suffix slices/sort plus naive LCP; not a linear-time suffix-array implementation or benchmark'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=True,indent=2))
