"""
QueueSnapshot 模型

队列快照表 - 定时采集队列积压数据和 Worker 数量统计
"""
from sqlalchemy import Column, Text, Integer, BigInteger, TIMESTAMP, Index
from datetime import datetime, timezone

from ..base import Base


class QueueSnapshot(Base):
    """
    队列快照表

    合并积压指标和 Worker 指标，定时采集：
    - 积压数据（backlog、pending_read、offset）
    - Worker 数量统计（online、offline、total）

    存储两类记录：
    - task 明细：每个 (queue, task_name) 一条，最细粒度
    - namespace 汇总：queue='', task_name=''，Worker 全局去重
    """
    __tablename__ = 'queue_snapshot'

    time_bucket = Column(
        TIMESTAMP(timezone=True),
        primary_key=True,
        comment='时间桶（分钟级别）'
    )
    namespace = Column(
        Text,
        primary_key=True,
        comment='命名空间'
    )
    queue = Column(
        Text,
        primary_key=True,
        comment='队列名称（namespace 汇总时为空字符串）'
    )
    task_name = Column(
        Text,
        primary_key=True,
        comment='任务名称（namespace 汇总时为空字符串）'
    )

    backlog = Column(
        Integer,
        nullable=False,
        default=0,
        comment='积压数量（已发送未ACK）= send_offset - ack_offset'
    )
    pending_read = Column(
        Integer,
        nullable=False,
        default=0,
        comment='待读取数量（已发送未读取）= send_offset - read_offset'
    )
    send_offset = Column(
        BigInteger,
        nullable=True,
        default=0,
        comment='发送 offset'
    )
    ack_offset = Column(
        BigInteger,
        nullable=True,
        default=0,
        comment='确认 offset'
    )
    read_offset = Column(
        BigInteger,
        nullable=True,
        default=0,
        comment='读取 offset'
    )

    online_count = Column(
        Integer,
        nullable=False,
        default=0,
        comment='在线 Worker 数量'
    )
    offline_count = Column(
        Integer,
        nullable=False,
        default=0,
        comment='离线 Worker 数量'
    )
    total_count = Column(
        Integer,
        nullable=False,
        default=0,
        comment='总 Worker 数量'
    )

    created_at = Column(
        TIMESTAMP(timezone=True),
        nullable=False,
        default=lambda: datetime.now(timezone.utc),
        comment='记录创建时间'
    )

    __table_args__ = (
        Index('idx_queue_snapshot_time', 'time_bucket'),
        Index('idx_queue_snapshot_ns_queue', 'namespace', 'queue'),
        Index('idx_queue_snapshot_ns_queue_task', 'namespace', 'queue', 'task_name'),
    )

    def to_dict(self):
        return {
            'time_bucket': self.time_bucket.isoformat() if self.time_bucket else None,
            'namespace': self.namespace,
            'queue': self.queue,
            'task_name': self.task_name,
            'backlog': self.backlog,
            'pending_read': self.pending_read,
            'send_offset': self.send_offset,
            'ack_offset': self.ack_offset,
            'read_offset': self.read_offset,
            'online_count': self.online_count,
            'offline_count': self.offline_count,
            'total_count': self.total_count,
            'created_at': self.created_at.isoformat() if self.created_at else None,
        }

    def __repr__(self):
        return (
            f"<QueueSnapshot("
            f"time_bucket={self.time_bucket}, "
            f"namespace={self.namespace}, "
            f"queue={self.queue}, "
            f"task={self.task_name}, "
            f"backlog={self.backlog}, "
            f"online={self.online_count}"
            f")>"
        )
