"""John Pye authentication helper - saves browser state after login."""

import json
from pathlib import Path

from playwright.sync_api import sync_playwright

DEFAULT_STATE_PATH = Path.home() / ".johnpye_state.json"


def login_and_save_state(state_path: Path = DEFAULT_STATE_PATH) -> None:
    """Open browser for manual login, then save state.

    Opens John Pye login page. User logs in manually.
    After login, press Enter in terminal to save state and close.

    Args:
        state_path: Where to save the browser state JSON.
    """
    print("Opening browser for John Pye login...")
    print("Please log in, then come back here and press Enter.")

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        context = browser.new_context()
        page = context.new_page()

        page.goto("https://www.johnpyeauctions.co.uk/Account/LogOn")

        input("\nPress Enter after logging in successfully...")

        # Save the browser state (cookies, localStorage, etc.)
        state = context.storage_state()
        with open(state_path, "w") as f:
            json.dump(state, f, indent=2)

        print(f"\nState saved to: {state_path}")

        browser.close()


def load_saved_state(state_path: Path = DEFAULT_STATE_PATH) -> dict | None:
    """Load previously saved browser state.

    Args:
        state_path: Path to state JSON file.

    Returns:
        State dict or None if file doesn't exist.
    """
    if not state_path.exists():
        return None
    with open(state_path) as f:
        return json.load(f)


if __name__ == "__main__":
    login_and_save_state()
