"""In-memory browser session ownership (single-operator; primary worker only)."""

from __future__ import annotations

import time
from dataclasses import dataclass, field


@dataclass
class BridgeSession:
    session_id: str
    admin_id: int
    viewport_w: int
    viewport_h: int
    created_at: float = field(default_factory=time.time)
    last_activity: float = field(default_factory=time.time)


_sessions: dict[str, BridgeSession] = {}


def register(session_id: str, admin_id: int, viewport_w: int, viewport_h: int) -> BridgeSession:
    sess = BridgeSession(session_id, admin_id, viewport_w, viewport_h)
    _sessions[session_id] = sess
    return sess


def get(session_id: str) -> BridgeSession | None:
    return _sessions.get(session_id)


def touch(session_id: str) -> None:
    sess = _sessions.get(session_id)
    if sess:
        sess.last_activity = time.time()


def remove(session_id: str) -> BridgeSession | None:
    return _sessions.pop(session_id, None)


def count_for_admin(admin_id: int) -> int:
    return sum(1 for s in _sessions.values() if s.admin_id == admin_id)


def session_ids_for_admin(admin_id: int) -> list[str]:
    return [sid for sid, s in _sessions.items() if s.admin_id == admin_id]


def total_count() -> int:
    return len(_sessions)
