"""
A small LOCAL model of how S3 decides whether an anonymous (not signed-in) request is allowed.
It follows the behaviour AWS documents for bucket policies, ACLs and the four Block Public Access
settings. It is a teaching model, NOT real S3: no network, no AWS account, no real objects.
"""
FLAGS = ("BlockPublicAcls", "IgnorePublicAcls", "BlockPublicPolicy", "RestrictPublicBuckets")

class Denied(Exception):
    pass

def _list(x): return x if isinstance(x, list) else [x]

def principal_is_public(p):
    return p == "*" or (isinstance(p, dict) and "*" in _list(p.get("AWS", [])))

def policy_is_public(doc):
    """True if any unconditioned Allow statement is open to everyone."""
    for s in _list(doc["Statement"]):
        if s["Effect"] == "Allow" and principal_is_public(s.get("Principal")) and "Condition" not in s:
            return True
    return False

def _grants(doc, action, resource):
    for s in _list(doc["Statement"]):
        if s["Effect"] != "Allow" or not principal_is_public(s.get("Principal")) or "Condition" in s:
            continue
        acts = _list(s["Action"])
        if not any(a in (action, "s3:*", "*") for a in acts):
            continue
        if any(r == resource or (r.endswith("/*") and resource.startswith(r[:-1])) for r in _list(s["Resource"])):
            return True
    return False

class SimBucket:
    def __init__(self, name, **bpa):
        self.name = name
        self.arn = f"arn:aws:s3:::{name}"
        self.objects = {}                 # key -> acl ("private" | "public-read")
        self.policy = None
        self.bucket_acl = "private"
        self.bpa = {f: False for f in FLAGS}
        self.bpa.update(bpa)

    def set_bpa(self, **flags):
        self.bpa.update(flags)

    def put_object(self, key, acl="private"):
        if acl == "public-read" and self.bpa["BlockPublicAcls"]:
            raise Denied("AccessDenied: BlockPublicAcls rejected the public ACL")
        self.objects[key] = acl

    def put_policy(self, doc):
        if policy_is_public(doc) and self.bpa["BlockPublicPolicy"]:
            raise Denied("AccessDenied: BlockPublicPolicy rejected the public policy")
        self.policy = doc

    def delete_policy(self):
        self.policy = None

    def anon_get(self, key):
        if key not in self.objects:
            return False, "no such key"
        if self.policy and policy_is_public(self.policy) and _grants(self.policy, "s3:GetObject", f"{self.arn}/{key}"):
            if self.bpa["RestrictPublicBuckets"]:
                return False, "public policy ignored (RestrictPublicBuckets)"
            return True, "allowed by public bucket policy"
        if self.objects[key] == "public-read":
            if self.bpa["IgnorePublicAcls"]:
                return False, "public ACL ignored (IgnorePublicAcls)"
            return True, "allowed by public object ACL"
        return False, "403 private"

    def anon_list(self):
        if self.policy and policy_is_public(self.policy) and _grants(self.policy, "s3:ListBucket", self.arn):
            if self.bpa["RestrictPublicBuckets"]:
                return False, []
            return True, sorted(self.objects)
        return False, []
