"""Utility to map browser pages to profiles for contextual logging."""

from __future__ import annotations
import weakref
from typing import TYPE_CHECKING, Optional

if TYPE_CHECKING:
    from playwright.async_api import Page

# Global mapping of Page instances to profile_id strings.
# Uses WeakKeyDictionary to avoid memory leaks when pages are closed.
_PAGE_TO_PROFILE_ID: weakref.WeakKeyDictionary[Page, str] = weakref.WeakKeyDictionary()


def register_page_to_profile(page: Page, profile_id: str) -> None:
    """Register a page with a profile_id for contextual logging lookup."""
    _PAGE_TO_PROFILE_ID[page] = profile_id


def get_profile_id_for_page(page: Page) -> Optional[str]:
    """Retrieve the profile_id associated with a page."""
    return _PAGE_TO_PROFILE_ID.get(page)
