"""Expiry-sweeper worker — sample app for the Cloud Infrastructure & DevOps course.

Plan A delivers a skeletal worker that just logs each sweep. Lesson 03
gives it real work to do against the docker-compose Postgres. Lesson 12
adds Prometheus metrics served on port 9090 (worker_jobs_processed_total,
worker_job_duration_seconds).
"""
from __future__ import annotations

import argparse
import logging
import os
import sys
import time

from prometheus_client import Counter, Histogram, start_http_server

JOBS = Counter(
    "worker_jobs_processed_total",
    "Worker expiry jobs processed",
    ["outcome"],
)
DUR = Histogram(
    "worker_job_duration_seconds",
    "Worker expiry job duration in seconds",
)


def sweep_once(log: logging.Logger) -> int:
    """Sweep expired URL records. Returns the number swept (0 in Plan A)."""
    # Lesson 03 replaces this with a DELETE against the Postgres URLs table.
    log.info("sweep tick: 0 records expired")
    return 0


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="URL expiry sweeper")
    parser.add_argument("--once", action="store_true", help="run a single sweep and exit")
    args = parser.parse_args(argv)

    logging.basicConfig(
        level=os.environ.get("LOG_LEVEL", "info").upper(),
        format="%(asctime)s %(levelname)s worker: %(message)s",
    )
    log = logging.getLogger("worker")

    if args.once:
        outcome = "ok"
        with DUR.time():
            try:
                sweep_once(log)
            except Exception:
                outcome = "err"
                log.exception("single sweep failed")
        JOBS.labels(outcome=outcome).inc()
        return 0

    # Start metrics HTTP server on port 9090 (scraped by Prometheus via pod annotation).
    metrics_port = int(os.environ.get("METRICS_PORT", "9090"))
    start_http_server(metrics_port)
    log.info("prometheus metrics available on :%s/metrics", metrics_port)

    interval = int(os.environ.get("SWEEP_INTERVAL_SECONDS", "30"))
    log.info("starting sweep loop (interval=%ss)", interval)
    while True:
        outcome = "ok"
        with DUR.time():
            try:
                sweep_once(log)
            except KeyboardInterrupt:
                log.info("interrupted; shutting down")
                return 0
            except Exception:
                outcome = "err"
                log.exception("worker batch failed")
        JOBS.labels(outcome=outcome).inc()
        try:
            time.sleep(interval)
        except KeyboardInterrupt:
            log.info("interrupted; shutting down")
            return 0


if __name__ == "__main__":
    sys.exit(main())
