"""CROWD-02: immutable ROI aggregate, not a synthetic tracked detection."""
from dataclasses import dataclass

from app.crowd_config import CROWD_MODEL


@dataclass(frozen=True)
class CrowdRegion:
    roi_label: str
    head_count: int
    person_count: int
    reference_count: int
    density_ratio: float
    status: str

    @classmethod
    def from_estimate(cls, config, estimate):
        ratio = estimate.head_count / config.reference_count
        status = ('DANGER' if ratio >= config.danger_ratio else
                  'WARNING' if ratio >= config.warning_ratio else
                  'CAUTION' if ratio >= config.caution_ratio else 'SAFE')
        return cls(config.roi_name, estimate.head_count, estimate.person_count,
                   config.reference_count, ratio, status)

    def payload(self):
        return dict(roiIndex=0, roiLabel=self.roi_label, headCount=self.head_count,
                    personCount=self.person_count, count=self.head_count,
                    referenceCount=self.reference_count, densityRatio=self.density_ratio,
                    status=self.status)


@dataclass(frozen=True)
class CrowdEvent:
    event_id: str
    frame: object
    roi_id: str
    region: CrowdRegion
    ai_recorded_at_wall_ms: int
    object_ref: None = None

    def __post_init__(self):
        if self.object_ref is not None or self.region.status != 'DANGER':
            raise ValueError('CROWD Events require a DANGER region without an object reference.')

    def payload(self):
        from app.contracts.visualization import frame_snapshot
        data = frame_snapshot(self.frame, self.frame.source_id)
        data.pop('objects')
        return dict(data, eventId=self.event_id, scenario='CROWD', categoryKey='crowd',
                    modelKey=CROWD_MODEL, trackId=None, roiId=self.roi_id, objectRef=None,
                    crowd=self.region.payload(), aiRecordedAtWallMs=self.ai_recorded_at_wall_ms,
                    clipUri=None, thumbnailUri=None, deliveryStatus='NOT_SUBMITTED')
