"""埋点事件批量落库。append-only,一次 commit 提交整批。"""
from __future__ import annotations

from sqlalchemy.orm import Session

from app.models.analytics_event import AnalyticsEvent
from app.schemas.analytics import AnalyticsBatchIn


def record_batch(db: Session, batch: AnalyticsBatchIn, *, client_ip: str | None) -> int:
    """把一批上报事件展开成多行落库(公共维度复制到每行),返回写入条数。"""
    rows = [
        AnalyticsEvent(
            event=e.event,
            props=e.props or None,
            device_id=batch.device_id,
            user_id=batch.user_id,
            session_id=e.session_id,
            client_ts=e.client_ts,
            sent_at=batch.sent_at,
            page=e.page,
            client_ip=client_ip or None,
            oem=batch.oem,
            os=batch.os,
            model=batch.model,
            app_ver=batch.app_ver,
            network=e.network,
            channel=batch.channel,
        )
        for e in batch.events
    ]
    db.add_all(rows)
    db.commit()
    return len(rows)
