"""Price Alert System — Threshold service layer.""" from __future__ import annotations import logging from typing import Any, Dict, List, Optional logger = logging.getLogger(__name__) class PriceWorker: """Business-logic service for Threshold operations in Price Alert System.""" def __init__( self, repo: Any, events: Optional[Any] = None, ) -> None: self._repo = repo self._events = events logger.debug("PriceWorker started") def trigger( self, payload: Dict[str, Any] ) -> Dict[str, Any]: """Execute the trigger workflow for a new Threshold.""" if "product_url" not in payload: raise ValueError("Missing required field: product_url") record = self._repo.insert( payload["product_url"], payload.get("current_price"), **{k: v for k, v in payload.items() if k not in ("product_url", "current_price")} ) if self._events: self._events.emit("threshold.triggerd", record) return record def snooze(self, rec_id: str, **changes: Any) -> Dict[str, Any]: """Apply *changes* to a Threshold and emit a change event.""" ok = self._repo.update(rec_id, **changes) if not ok: raise KeyError(f"Threshold {rec_id!r} not found") updated = self._repo.fetch(rec_id) if self._events: self._events.emit("threshold.snoozed", updated) return updated def archive(self, rec_id: str) -> None: """Remove a Threshold and emit a removal event.""" ok = self._repo.delete(rec_id) if not ok: raise KeyError(f"Threshold {rec_id!r} not found") if self._events: self._events.emit("threshold.archived", {"id": rec_id}) def search( self, product_url: Optional[Any] = None, status: Optional[str] = None, limit: int = 50, ) -> List[Dict[str, Any]]: """Search thresholds by *product_url* and/or *status*.""" filters: Dict[str, Any] = {} if product_url is not None: filters["product_url"] = product_url if status is not None: filters["status"] = status rows, _ = self._repo.query(filters, limit=limit) logger.debug("search thresholds: %d hits", len(rows)) return rows @property def stats(self) -> Dict[str, int]: """Quick summary of Threshold counts by status.""" result: Dict[str, int] = {} for status in ("active", "pending", "closed"): _, count = self._repo.query({"status": status}, limit=0) result[status] = count return result