import asyncio
import random

from fast_telemetry.integrations.worker import WorkerMetrics

metrics = WorkerMetrics(service_name="nightly_job", env="prod")


class PaymentError(Exception):
    pass


class DatabaseError(Exception):
    pass


@metrics.measure_task("heavy_calculation")
async def heavy_task():
    await asyncio.sleep(random.uniform(0.1, 0.5))


@metrics.track_exception
async def risky_task():
    if random.random() < 0.3:
        raise PaymentError("Payment declined")
    if random.random() < 0.1:
        raise DatabaseError("Connection lost")
    await asyncio.sleep(0.05)


async def run_worker():
    metrics.start_server(port=8000)
    while True:
        await risky_task()
        await heavy_task()
        await asyncio.sleep(5)


# async def run_batch_job():
#     async with metrics.track_job(gateway_url="http://pushgateway:9091"):
#         await do_heavy_calculation()
#         metrics.inc_error("calc_error")


if __name__ == "__main__":
    asyncio.run(run_worker())
