import uuid

from sqlalchemy import Column, Integer, BigInteger, Boolean, Float, SmallInteger, Unicode

from .meta import Base, RBase, UUIDType, now_timestamp, foreign_key


class PageSession(RBase, Base):
    """Anonymous page visit signal — one row per page view.

    No cookies, no IPs, no fingerprints.  The client sends a single
    beacon (~300 bytes JSON) on page unload.
    """

    id = Column(UUIDType, primary_key=True, index=True)
    shop_id = Column(UUIDType, foreign_key("Shop", "id"), nullable=False)
    product_id = Column(UUIDType, foreign_key("Product", "id"), nullable=False)
    created_timestamp = Column(BigInteger, nullable=False)

    # Presence
    wall_clock_ms = Column(Integer, nullable=True)
    visible_ms = Column(Integer, nullable=True)
    active_ms = Column(Integer, nullable=True)

    # Scroll
    scroll_depth_max = Column(Float, nullable=True)
    scroll_direction_changes = Column(Integer, nullable=True)

    # Media (nullable — only populated when page has video/audio)
    media_duration_ms = Column(Integer, nullable=True)
    media_play_ms = Column(Integer, nullable=True)
    media_play_count = Column(SmallInteger, nullable=True)
    media_pause_count = Column(SmallInteger, nullable=True)
    media_seek_count = Column(SmallInteger, nullable=True)
    media_seek_back_count = Column(SmallInteger, nullable=True)
    media_speed = Column(Float, nullable=True)
    media_completed = Column(Boolean, nullable=True)
    media_percent_played = Column(Float, nullable=True)

    # Context
    is_ring_entry = Column(Boolean, nullable=True)
    ring_position = Column(SmallInteger, nullable=True)
    referrer_class = Column(SmallInteger, nullable=True)  # 0-4
    referrer_domain = Column(Unicode(128), nullable=True)  # e.g. "google.com"
    referrer_query = Column(Unicode(256), nullable=True)  # search engine query
    device_class = Column(SmallInteger, nullable=True)  # 0-2
    is_owner = Column(Boolean, nullable=True)  # shop owner/editor viewing own product

    def __init__(self):
        self.id = uuid.uuid1()
        self.created_timestamp = now_timestamp()
