import Control.Monad

main :: IO ()
main = do
  n <- readLn
  ls <- replicateM n getLine
  mapM_ putStrLn $ solve ls

solve :: [String] -> [String]
solve = map check
  where
    check :: String -> String
    check (x:y:r)
      | x /= '>' = "NA"
      | y == '\'' = checkA r
      | y == '^' = checkB r
      | otherwise = "NA"
      where
        checkA :: String -> String
        checkA s
          | s == [] = "NA"
          | last s /= '~' = "NA"
          | filter ('=' /=) s /= "#~" = "NA"
          | reverse s' == s' = "A"
          | otherwise = "NA"
          where s' = init s
        checkB :: String -> String
        checkB s
          | s == [] = "NA"
          | (last s /= '~') || ((last . init $ s) /= '~') = "NA"
          | checkB2 (init (init s)) = "B"
          | otherwise = "NA"
          where
            checkB2 :: String -> Bool
            checkB2 [] = True
            checkB2 [x] = False
            checkB2 (x:y:r) = (x == 'Q') && (y == '=') && (checkB2 r)