"""新手引导(及后续)埋点事件表。

每行 = 客户端上报的一条行为埋点,按「Who / When / Where / What / How」五维组织:
- What :event(事件名,如 video_play)+ props(事件专属属性,JSON)
- Who  :device_id(硬件级设备标识)+ user_id(登录后才有,可空)
- When :client_ts(端事件时间 epoch ms)+ session_id(本次引导会话)+ sent_at(端上报时间)
         + created_at(服务端接收时间 = server_at)
- Where:page(引导步/页面)+ client_ip(服务端从 X-Forwarded-For 取)
- How  :oem / os / model / app_ver / network / channel(设备与环境)

append-only,不更新;客户端批量上报(见 app/api/v1/analytics.py),admin 同库直接查(见
app/admin/routers/event_logs.py)。未登录态也允许上报(user_id 为空),故 user_id 不设外键、只索引。
"""
from __future__ import annotations

from datetime import datetime

from sqlalchemy import JSON, BigInteger, DateTime, Integer, String, func
from sqlalchemy.orm import Mapped, mapped_column

from app.db.base import Base


class AnalyticsEvent(Base):
    __tablename__ = "analytics_event"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)

    # ---- What:做了什么 ----
    event: Mapped[str] = mapped_column(String(64), index=True, nullable=False)
    props: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    # ---- Who:谁 ----
    device_id: Mapped[str] = mapped_column(String(64), index=True, nullable=False)
    user_id: Mapped[int | None] = mapped_column(Integer, index=True, nullable=True)

    # ---- When:何时 ----
    session_id: Mapped[str | None] = mapped_column(String(64), index=True, nullable=True)
    client_ts: Mapped[int] = mapped_column(BigInteger, nullable=False)  # 端事件时间 epoch ms
    sent_at: Mapped[int | None] = mapped_column(BigInteger, nullable=True)  # 端上报时间 epoch ms

    # ---- Where:何地 ----
    page: Mapped[str | None] = mapped_column(String(64), nullable=True)
    client_ip: Mapped[str | None] = mapped_column(String(64), nullable=True)

    # ---- How:用什么环境 ----
    oem: Mapped[str | None] = mapped_column(String(32), nullable=True)
    os: Mapped[str | None] = mapped_column(String(32), nullable=True)
    model: Mapped[str | None] = mapped_column(String(64), nullable=True)
    app_ver: Mapped[str | None] = mapped_column(String(32), nullable=True)
    network: Mapped[str | None] = mapped_column(String(16), nullable=True)
    channel: Mapped[str | None] = mapped_column(String(32), nullable=True)

    # 服务端接收时间(= When.server_at);客户端时间不可信,以此为权威落库时刻。
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), index=True, nullable=False
    )

    def __repr__(self) -> str:  # pragma: no cover
        return f"<AnalyticsEvent id={self.id} event={self.event} device={self.device_id}>"
