"""SessionManager — save and restore authenticated browser state.

After a successful login, the storage state (cookies + localStorage) can be
saved to a JSON file.  On subsequent runs, BrowserManager restores that state
so tests skip the login step entirely.
"""

from __future__ import annotations

import json
import logging
from pathlib import Path

from playwright.sync_api import BrowserContext

log = logging.getLogger("antiqa.browser")

DEFAULT_SESSION_DIR = "logs/sessions"


class SessionManager:
    """Persist and restore Playwright storage state."""

    def __init__(self, session_dir: str | Path = DEFAULT_SESSION_DIR) -> None:
        self.session_dir = Path(session_dir)
        self.session_dir.mkdir(parents=True, exist_ok=True)

    def _path_for(self, name: str) -> Path:
        return self.session_dir / f"{name}.json"

    def save(self, context: BrowserContext, name: str = "default") -> Path:
        """Save the current browser context's storage state."""
        path = self._path_for(name)
        state = context.storage_state()
        path.write_text(json.dumps(state, indent=2))
        log.info("Session saved to %s", path)
        return path

    def load_path(self, name: str = "default") -> Path | None:
        """Return the path to a saved session, or None if it doesn't exist."""
        path = self._path_for(name)
        if path.is_file():
            return path
        return None

    def exists(self, name: str = "default") -> bool:
        return self._path_for(name).is_file()

    def delete(self, name: str = "default") -> bool:
        """Delete a saved session. Returns True if it existed."""
        path = self._path_for(name)
        if path.is_file():
            path.unlink()
            log.info("Session deleted: %s", path)
            return True
        return False

    def list_sessions(self) -> list[str]:
        """Return names of all saved sessions."""
        return [p.stem for p in self.session_dir.glob("*.json")]
