from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Optional


@dataclass
class BrowserConfig:
    headless: bool = False
    browser_channel: Optional[str] = None  # e.g. "chrome"


class PlaywrightSession:
    """
    Wrapper around Playwright to load an authenticated `storage_state` JSON.
    """

    def __init__(self, *, storage_state: Path, config: BrowserConfig | None = None) -> None:
        self.storage_state = storage_state
        self.config = config or BrowserConfig()

    def run(self, *, job_fn) -> None:
        # Imports are intentionally inside to keep the package importable without playwright installed.
        from playwright.sync_api import sync_playwright

        if not self.storage_state.exists():
            raise FileNotFoundError(f"storage_state not found: {self.storage_state}")

        with sync_playwright() as p:
            if self.config.browser_channel:
                browser = p.chromium.launch(channel=self.config.browser_channel, headless=self.config.headless)
            else:
                browser = p.chromium.launch(headless=self.config.headless)

            context = browser.new_context(storage_state=str(self.storage_state))
            page = context.new_page()
            try:
                job_fn(page)
            finally:
                context.close()
                browser.close()

