normalizeQuery :: [UnnormalizedQueryItem] -> Maybe Query
normalizeQuery l =
  Query
    <$> ( NonEmpty.nonEmpty
            . reverse
            . fmap unsafeToQI
            . foldr simplify []
            . reverse
            $ l
        )
  where
    unsafeToQI :: UnnormalizedQueryItem -> QueryItem
    unsafeToQI (GlobInput g) = Glob g
    unsafeToQI i =
      error $
        "`normalizeQuery` did not remove an "
          <> show i
          <> ". This is a bug in `mars`"
    simplify :: UnnormalizedQueryItem -> [UnnormalizedQueryItem] -> [UnnormalizedQueryItem]
    simplify CurrentLevel processed = processed
    simplify LevelAbove processed = drop 1 processed
    simplify item processed = item : processed
normalizeQuery :: [UnnormalizedQueryItem] -> Maybe Query
normalizeQuery l =
  Query
    <$> ( NonEmpty.nonEmpty
            . reverse
            . fmap unsafeToQI
            . foldr simplify []
            . reverse
            $ l
        )
  where
    unsafeToQI :: UnnormalizedQueryItem -> QueryItem
    unsafeToQI (GlobInput g) = Glob g
    unsafeToQI i =
      error $
        "`normalizeQuery` did not remove an "
          <> show i
          <> ". This is a bug in `mars`"
    simplify :: UnnormalizedQueryItem -> [UnnormalizedQueryItem] -> [UnnormalizedQueryItem]
    simplify CurrentLevel processed = processed
    simplify LevelAbove processed = drop 1 processed
    simplify item processed = item : processed
normalizeQuery l =
  Query
    <$> ( NonEmpty.nonEmpty
            . reverse
            . fmap unsafeToQI
            . foldr simplify []
            . reverse
            $ l
        )
  where
    unsafeToQI :: UnnormalizedQueryItem -> QueryItem
    unsafeToQI (GlobInput g) = Glob g
    unsafeToQI i =
      error $
        "`normalizeQuery` did not remove an "
          <> show i
          <> ". This is a bug in `mars`"
    simplify :: UnnormalizedQueryItem -> [UnnormalizedQueryItem] -> [UnnormalizedQueryItem]
    simplify CurrentLevel processed = processed
    simplify LevelAbove processed = drop 1 processed
    simplify item processed = item : processed