from collections import defaultdict
from .emissions import calculate_co2

def aggregate_device_data(devices: list[dict], data: list[dict]):
    total_by_utility = defaultdict(float)
    device_breakdown = []

    for device in devices:
        usage = sum(d["value"] for d in data if d["device_id"] == device["id"])
        total_by_utility[device["utility_type"]] += usage
        device_breakdown.append({
            "device_name": device["name"],
            "utility": device["utility_type"],
            "usage": usage,
        })

    return dict(total_by_utility), device_breakdown

def compute_emissions(total_by_utility: dict[str, float]):
    emissions = {}
    total = 0.0
    for utility, usage in total_by_utility.items():
        co2 = calculate_co2(utility, usage)
        emissions[utility] = co2
        total += co2
    emissions["total"] = total
    return emissions
