What was the purpose of the Alhambra?

The Alhambra was built for defense purposes and as a city in its own right comprising three parts: the alcazaba (military residential citadel), the alcázar (the palace) and the medina (the city).