import logging

from tqdmpromproxy.bucket import PrometheusBucket
from tqdmpromproxy.snapshot import TqdmSnapshot


class BucketManager():
    def __init__(self):
        self.buckets: list[PrometheusBucket] = []

    def update(self, snapshot: TqdmSnapshot):
        '''Called asynchronously with snapshot events'''
        for b in self.buckets:
            if b.matches(snapshot):
                b.upsert(snapshot)
                return

        self.buckets.append(PrometheusBucket.from_instance(snapshot))

    def export(self, out_stream):
        logging.info("Begin bucket dump (%d) buckets", len(self.buckets))
        out_stream.write(f"# total categories {len(self.buckets)}")

        for b in self.buckets:
            logging.info("Dumping bucket %s -> %s", b.bucket_key, b)

            for line in b.to_prometheus_lines():
                out_stream.write(line)
                out_stream.write("\n")

        logging.info("End bucket dump")
