import random
import re

_CORPUS: list[str] = []


def _load_corpus() -> None:
  candidate_paths = [
    '/fuzzer/additional.sql',
  ]
  for p in candidate_paths:
    if not p:
      continue
    try:
      with open(p, 'r', encoding='latin-1') as f:
        content = f.read()
    except OSError:
      continue
    chunks = [c.strip() for c in content.split('---') if c.strip()]
    chunks = [
      c for c in chunks if any(not ln.strip().startswith('--') and ln.strip()
                               for ln in c.split('\n'))
    ]
    if chunks:
      _CORPUS.extend(chunks)
      return


_load_corpus()


def mut_splice_append(s: str) -> str:
  """Append a random chunk from the corpus"""

  if not _CORPUS:
    return s

  return s + '\n' + random.choice(_CORPUS)


def mut_splice_prepend(s: str) -> str:
  """Prepend a random chunk from the corpus"""

  if not _CORPUS:
    return s

  return random.choice(_CORPUS) + '\n' + s


def mut_splice_replace(s: str) -> str:
  """Replace s etirely with a random corpus chunk"""

  if not _CORPUS:
    return s

  return random.choice(_CORPUS)


def mut_splice_intersperse(s: str) -> str:
  """Insert a random corpus chunk between two random statements of s"""

  if not _CORPUS:
    return s
  parts = re.split(r'(?<=;)\s*\n', s)
  if len(parts) < 2:
    return s + '\n' + random.choice(_CORPUS)
  i = random.randint(1, len(parts) - 1)

  return '\n'.join(parts[:i] + [random.choice(_CORPUS)] + parts[i:])
