import asyncio
import aiohttp
import sys
from typing import List, Dict, Any, Tuple
from collections import defaultdict
# Define the API endpoints
USERS_URL = "https://jsonplaceholder.typicode.com/users"
TODOS_URL = "https://jsonplaceholder.typicode.com/todos"
async def fetch_json(session: aiohttp.ClientSession, url: str) -> Any:
"""
Fetches JSON data from a given URL using an aiohttp session.
Args:
session: The aiohttp client session.
url: The URL to fetch data from.
Returns:
The JSON data decoded into a Python object (typically list or dict).
Raises:
aiohttp.ClientError: If an HTTP error occurs during the request.
json.JSONDecodeError: If the response body is not valid JSON.
"""
async with session.get(url) as response:
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
return await response.json()
async def fetch_all_data(session: aiohttp.ClientSession) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
"""
Fetches users and todos data concurrently.
Args:
session: The aiohttp client session.
Returns:
A tuple containing the list of users and the list of todos.
Exits the script if fetching fails.
"""
try:
users, todos = await asyncio.gather(
fetch_json(session, USERS_URL),
fetch_json(session, TODOS_URL)
)
return users, todos
except (aiohttp.ClientError, Exception) as e:
# Catch aiohttp errors and other potential exceptions during fetch/json decode
print(f"Error fetching data: {e}", file=sys.stderr)
sys.exit(1) # Exit gracefully as required
def process_data(users: List[Dict[str, Any]], todos: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Processes user and todo data to calculate completion percentages,
filter users by address suite, and return the top users by percentage.
Args:
users: A list of user dictionaries.
todos: A list of todo dictionaries.
Returns:
A list of dictionaries, where each dictionary contains user information
and their calculated completion percentage, sorted in descending order
of percentage and filtered for users in suites.
"""
# Map todos to users
user_todos: Dict[int, List[Dict[str, Any]]] = defaultdict(list)
for todo in todos:
user_todos[todo['userId']].append(todo)
user_completion_data: List[Dict[str, Any]] = []
for user in users:
user_id = user['id']
user_specific_todos = user_todos.get(user_id, [])
total_todos = len(user_specific_todos)
completed_todos = sum(1 for todo in user_specific_todos if todo['completed'])
completion_percentage = 0.0
if total_todos > 0:
completion_percentage = (completed_todos / total_todos) * 100
# Store user info along with the calculated percentage
user_completion_data.append({
'user': user,
'completion_percentage': completion_percentage
})
# Filter users who live in a suite
filtered_users = [
data for data in user_completion_data
if 'address' in data['user'] and 'suite' in data['user']['address']
and "Suite" in data['user']['address']['suite']
]
# Sort filtered users by completion percentage descending
sorted_users = sorted(filtered_users, key=lambda x: x['completion_percentage'], reverse=True)
# Return the top 3 users
return sorted_users[:3]
def generate_report(top_users_data: List[Dict[str, Any]]) -> str:
"""
Generates a Markdown formatted report for the top users.
Args:
top_users_data: A list of dictionaries for the top users,
each containing 'user' info and 'completion_percentage'.
Returns:
A string containing the Markdown formatted report.
"""
report_lines = ["# Top To-Do Performers (Living in Suites)", ""]
if not top_users_data:
report_lines.append("No users living in suites found with completion data.")
return "\n".join(report_lines)
for i, data in enumerate(top_users_data):
user = data['user']
percentage = data['completion_percentage']
name = user.get('name', 'N/A')
company_name = user.get('company', {}).get('name', 'N/A')
city = user.get('address', {}).get('city', 'N/A')
report_lines.append(f"{i + 1}. **{name}**")
report_lines.append(f" - Company: {company_name}")
report_lines.append(f" - City: {city}")
report_lines.append(f" - To-Do Completion: {percentage:.2f}%")
report_lines.append("") # Add a blank line between entries
return "\n".join(report_lines)
async def main():
"""
Main asynchronous function to orchestrate data fetching, processing, and reporting.
"""
# Use a context manager for the aiohttp session
async with aiohttp.ClientSession() as session:
# Fetch data, handles errors and exits if necessary
users, todos = await fetch_all_data(session)
# Process data to find top users in suites
top_users_suite = process_data(users, todos)
# Generate the Markdown report
report = generate_report(top_users_suite)
# Print the report to standard output
print(report)
if __name__ == "__main__":
# Run the main asynchronous function
asyncio.run(main())