#!/usr/bin/env python3
"""
chatgpt-login/scripts/load_session.py
---------------------------------------
Loads a previously saved ChatGPT session (cookies + localStorage) and opens
a ready-to-use browser page. Returns the page object for further automation.

Intended for import inside another script:

    from load_session import open_chatgpt_session
    with open_chatgpt_session() as (browser_ctx, page):
        page.goto("https://chatgpt.com/")
        # ... do stuff

Or run directly to verify a saved session is still valid:
    python3 load_session.py [--session /path/to/session.json]

Environment overrides:
    CHATGPT_SESSION  — Path to the session JSON file
    CHATGPT_PROXY    — SOCKS5 proxy URL (defaults to socks5://172.20.0.1:1055)
"""

import argparse
import contextlib
import os
import subprocess
import sys
import time

from camoufox.sync_api import Camoufox

DEFAULT_PROXY   = "socks5://172.20.0.1:1055"
DEFAULT_SESSION = "/workspace/group/chatgpt-session.json"
SCREENSHOT_DIR  = "/workspace/group/screenshots/chatgpt-login"


def tc_proxy() -> str:
    result = subprocess.run(["tc", "proxy"], capture_output=True, text=True)
    url = result.stdout.strip()
    return url if url and not result.returncode else ""


def shot(page, name: str, timeout: int = 60_000) -> None:
    os.makedirs(SCREENSHOT_DIR, exist_ok=True)
    path = os.path.join(SCREENSHOT_DIR, f"{name}.png")
    try:
        page.screenshot(path=path, timeout=timeout)
        print(f"  [screenshot] {path}")
    except Exception as exc:
        print(f"  [screenshot failed] {name}: {exc}")


@contextlib.contextmanager
def open_chatgpt_session(session_path: str = None, proxy: str = None):
    """
    Context manager that yields (context, page) with ChatGPT already loaded
    from a saved session file. Re-raises if the session has expired.

    Usage:
        with open_chatgpt_session() as (ctx, page):
            page.goto("https://chatgpt.com/")
            ...
    """
    session_path = (session_path
                    or os.environ.get("CHATGPT_SESSION")
                    or DEFAULT_SESSION)
    proxy = (proxy
             or os.environ.get("CHATGPT_PROXY")
             or tc_proxy()
             or DEFAULT_PROXY)

    if not os.path.exists(session_path):
        raise FileNotFoundError(
            f"Session file not found: {session_path}\n"
            "Run login.py first to create it."
        )

    proxy_cfg = {"server": proxy} if proxy else None

    with Camoufox(headless=True, proxy=proxy_cfg, geoip=bool(proxy_cfg)) as browser:
        context = browser.new_context(storage_state=session_path)
        page    = context.new_page()

        page.goto("https://chatgpt.com/", wait_until="domcontentloaded", timeout=30_000)
        time.sleep(3)

        current_url = page.url
        if "auth.openai.com" in current_url or "login" in current_url:
            raise RuntimeError(
                "Session has expired or is invalid — the browser was redirected to "
                f"the login page: {current_url}\n"
                "Re-run login.py to refresh the session."
            )

        yield context, page


def verify_session(session_path: str = None) -> bool:
    """
    Verify a saved session is still valid. Prints status and returns True/False.
    """
    session_path = session_path or os.environ.get("CHATGPT_SESSION") or DEFAULT_SESSION

    if not os.path.exists(session_path):
        print(f"✗ Session file not found: {session_path}")
        return False

    print(f"[*] Loading session from: {session_path}")
    try:
        with open_chatgpt_session(session_path=session_path) as (ctx, page):
            final_url = page.url
            shot(page, "session_verify")
            print(f"✓ Session is VALID — on: {final_url}")
            return True
    except RuntimeError as exc:
        print(f"✗ Session is EXPIRED:\n  {exc}")
        return False
    except Exception as exc:
        print(f"✗ Error loading session: {exc}")
        return False


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Verify a saved ChatGPT session.")
    parser.add_argument("--session", default=None,
                        help=f"Path to session JSON (default: {DEFAULT_SESSION})")
    args = parser.parse_args()

    ok = verify_session(session_path=args.session)
    sys.exit(0 if ok else 1)
