How does WP knows which template to use for a page

The native logic of template choice is contained in file aptly named template-loader.php. It processes the current context and calls respective get_*_template() functions, until a match is found.

This process results in what is called Template Hierarchy.

However as it was pointed out this only covers native core logic. Plugins can wildly customize this process at different stages or skip it altogether.