from __future__ import annotations

import os
import boto3


def delete_buckets_with_tag(tag_value: str, region: str):
    s3 = boto3.resource("s3", region_name=region)
    client = s3.meta.client
    for b in client.list_buckets().get("Buckets", []):
        name = b["Name"]
        try:
            tags = client.get_bucket_tagging(Bucket=name).get("TagSet", [])
        except Exception:
            tags = []
        if any(t["Key"] == "resource-tag" and t["Value"] == tag_value for t in tags):
            bucket = s3.Bucket(name)
            # delete objects and versions
            bucket.object_versions.delete()
            bucket.objects.all().delete()
            client.delete_bucket(Bucket=name)




def main():
    region = os.getenv("AWS_REGION", "us-east-1")
    tag = os.getenv("RESOURCE_TAG")
    if not tag:
        print("RESOURCE_TAG is required to teardown tagged resources.")
        return
    delete_buckets_with_tag(tag, region)
    print("Teardown complete for tag:", tag)


if __name__ == "__main__":
    main()


