#!awk -f

function uwuify(s, o) {
  o = s

  # r/l -> w/W
  o = gensub(/[rl]/, "w", "g", o)
  o = gensub(/[RL]/, "W", "g", o)

  # n + vowel -> ny
  o = gensub(/N([AEIOU])/, "NY\\1", "g", o)
  o = gensub(/([nN])([aeiouAEIOU])/, "\\1y\\2", "g", o)

  # soft c before e/i
  o = gensub(/c([ie])/, "sh\\1", "g", o)
  o = gensub(/C([ie])/, "Sh\\1", "g", o)
  o = gensub(/C([IE])/, "SH\\1", "g", o)

  # th -> d
  o = gensub(/th/, "d", "g", o)
  o = gensub(/Th/, "D", "g", o)
  o = gensub(/TH/, "D", "g", o)

  # ove -> uv
  o = gensub(/ove/, "uv", "g", o)
  o = gensub(/OVE/, "UV", "g", o)

  # ing -> in’
  o = gensub(/ing\b/, "in’", "g", o)
  o = gensub(/ING\b/, "IN’", "g", o)

  # punctuation uwuifier
  o = gensub(/!+/, " owo~ ", "g", o)
  o = gensub(/\?+/, " uwu?", "g", o)
  o = gensub(/\.{3}/, "… >w< ", "g", o)

  return o
}

function uwuify_line(line,   pre, post, uw_pre, diff, fullseq, num, newnum, newseq) {
  if (match(line, /^(.*:)/)) {
    pre  = substr(line, 1, RLENGTH)
    post = substr(line, RLENGTH + 1)

    uw_pre = uwuify(pre)
    diff = length(uw_pre) - length(pre)

    if (match(uw_pre, /\033\[[0-9]+C/)) {
      fullseq = substr(uw_pre, RSTART, RLENGTH)
      if (match(fullseq, /\033\[([0-9]+)C/, m)) {
        num = m[1]
        newnum = num - diff
        if (newnum < 0) newnum = 0
        newseq = "\033[" newnum "C"
        uw_pre = substr(uw_pre, 1, RSTART - 1) newseq substr(uw_pre, RSTART + RLENGTH)
      }
    }

    return uw_pre uwuify(post)
  }
  return uwuify(line)
}

{
  # Kitty image protocol lines stay raw
  if ($0 ~ /\033_G/) {
    print $0
  } else if ($0 ~ /\033\[[0-9]+C/) {
    out = uwuify_line($0)
    print out
  } else {
    out = uwuify($0)
    print out
  }
}
