I agree with RJean and acraven that you don't have the time to visit 3 countries in 3 weeks. So I recommend either spending all 3 weeks in Spain OR split the time between Spain and Portugal. Perhaps 2 weeks in Spain and 1 week in Portugal, or 1.5 weeks in Spain and 1.5 weeks in Portugal, depending on your interests and what you want to see and do.
I also want to repeat what acraven said about the heat in Spain, and especially in Andalusia. I LOVE Andalusia but we went in September 2017. We had 80's in Madrid, Toledo, Cordoba, and Granada, and low 90's in Seville. We were in Seville in late September. Please look at weather data sites. It is very common to have temps in the 90's to 100's in Andalusia during the summer. I THINK, but not sure, Barcelona may be a little bit cooler but I hear it's very humid. When I was planning our trip, I read trip reports from people who were in Andalusia during the summer months, and they talked about being drenched in sweat after 10 minutes outside. If you still decide on Andalusia, make sure you have hotels with pools, leave early in the morning for sightseeing, then return in the afternoon for swimming in the pool and to cool off in your air-conditioned hotel/apartment. Then return for sightseeing in the evening.
Lisbon - 4 nights
Sintra - 1 or 2 nights
Cascais - on the water - might be cooler - could spend a day here or stay overnight.
I haven't been anywhere else in Portugal so can't really comment
Seville - 4 nights minimum or 5 nights
Granada - 2 or 3 nights (might be a bit cooler since it's in the mountains)
Cordoba - 2 nights
Malaga - 2 or 3 nights - on the Mediterranean so might be cooler, and you can cool off in the water. Malaga was the coolest place on our trip, in the high 70's (mid to late September). It's an under-rated city; we loved it; there is sightseeing but as I already said, it could be a place to cool off and it's nice to have some coastal ambience.
Madrid - 3 or 4 nights, especially if you like art museums. And the museums will be air-conditioned, so a place to get some respite from the heat.
You can fly from Lisbon to Seville via TAP Airlines.
Use the trains or buses to all destinations in Spain unless you want to see the white hill towns, where a car would be better.
You can fly home from Malaga or Madrid.