from __future__ import annotations import uuid from datetime import datetime from typing import Any from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.models.detected_change import DetectedChange from app.models.enums import ChangeType class DetectedChangeRepository: def __init__(self, db: AsyncSession) -> None: self.db = db async def get_recent_for_source_and_type( self, source_id: uuid.UUID, change_type: ChangeType, since: datetime ) -> DetectedChange | None: """Most recent DetectedChange of this type for this source within the cooldown window - used both to flag repeats (lower significance) and to suppress exact duplicates (see change_detection_service.py).""" result = await self.db.execute( select(DetectedChange) .where( DetectedChange.source_id == source_id, DetectedChange.change_type == change_type, DetectedChange.created_at >= since, ) .order_by(DetectedChange.created_at.desc()) .limit(1) ) return result.scalar_one_or_none() async def create(self, **kwargs: Any) -> DetectedChange: change = DetectedChange(**kwargs) self.db.add(change) await self.db.flush() return change async def list_for_company( self, company_id: uuid.UUID, limit: int = 100 ) -> list[DetectedChange]: result = await self.db.execute( select(DetectedChange) .where(DetectedChange.company_id == company_id) .order_by(DetectedChange.created_at.desc()) .limit(limit) ) return list(result.scalars().all())