from google.cloud import compute_v1

def stop_instance(project_id, zone, instance_name):
    client = compute_v1.InstancesClient()
    
    print(f"Stopping instance {instance_name} in {zone}...")
    
    operation = client.stop(project=project_id, zone=zone, instance=instance_name)
    operation.result() # Wait for operation to complete
    
    print(f"Instance {instance_name} stopped.")

def stop_instances_by_label(project_id, label_key, label_value):
    client = compute_v1.InstancesClient()
    request = compute_v1.AggregatedListInstancesRequest(project=project_id)
    
    for zone, response in client.aggregated_list(request=request):
        if response.instances:
            for instance in response.instances:
                if instance.labels.get(label_key) == label_value:
                    zone_name = instance.zone.split("/")[-1]
                    stop_instance(project_id, zone_name, instance.name)

if __name__ == "__main__":
    # Example: Stop instances with label env=dev
    stop_instances_by_label("my-project-id", "env", "dev")
