#!/usr/bin/env python3
"""AuthAPI NotebookLM metadata bridge. Python stdlib only; no remote command RPC.

Google credentials remain exclusively with the local notebooklm CLI. This process
uploads only validated notebook IDs/titles and fixed status codes. Keep it running
to keep the website online; Ctrl-C stops it. Re-run a newly generated command to
reconnect. The bridge credential lives only in memory, never in a local file.
"""
import argparse
import json
import re
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request

MAX_OUTPUT = 2 * 1024 * 1024
BROWSERS = {'chrome', 'firefox', 'brave', 'edge', 'chromium', 'vivaldi', 'opera', 'arc'}


class Revoked(Exception):
    pass


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None  # Never forward secrets to a redirect destination.


def request(origin, action, body, credential=None):
    data = json.dumps(body).encode('utf-8')
    headers = {'Content-Type': 'application/json'}
    if credential:
        headers['Authorization'] = 'Bearer ' + credential
    req = urllib.request.Request(origin + '/api/notebooklm/' + action, data=data, headers=headers)
    try:
        with urllib.request.build_opener(NoRedirect).open(req, timeout=20) as response:
            raw = response.read(65537)
            if len(raw) > 65536:
                raise ValueError('Server response too large')
            return json.loads(raw)
    except urllib.error.HTTPError as error:
        if error.code in (401, 403):
            raise Revoked('Pairing code or bridge revoked/expired. Generate a new command on the website.') from None
        raise RuntimeError('Website returned HTTP ' + str(error.code)) from None


def run_cli(args, timeout=60):
    """No shell, fixed argument allowlist at call sites; bounded stdout/stderr."""
    with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as err:
        with subprocess.Popen(['notebooklm'] + args, stdout=out, stderr=err) as proc:
            deadline = time.monotonic() + timeout
            while proc.poll() is None:
                if time.monotonic() >= deadline or out.tell() > MAX_OUTPUT or err.tell() > MAX_OUTPUT:
                    proc.kill()
                    proc.wait()
                    raise ValueError('CLI timed out or output too large')
                time.sleep(0.05)
            out.seek(0)
            result = out.read(MAX_OUTPUT + 1)
            if len(result) > MAX_OUTPUT:
                raise ValueError('CLI output too large')
            return proc.returncode, result


def list_notebooks():
    if not shutil.which('notebooklm'):
        return {'state': 'cli_missing', 'notebooks': []}
    try:
        code, raw = run_cli(['list', '--json'])
        if code:
            # Do not upload/log CLI stderr: it could contain sensitive auth data.
            return {'state': 'login_required', 'notebooks': []}
        data = json.loads(raw)
        rows = data.get('notebooks') if isinstance(data, dict) else data
        if not isinstance(rows, list) or len(rows) > 500:
            raise ValueError('Unsupported or oversized notebook list')
        notebooks = []
        seen = set()
        for row in rows:
            notebook_id = row.get('id')
            title = row.get('title')
            if (not isinstance(notebook_id, str) or not re.fullmatch(r'[a-zA-Z0-9_-]{1,128}', notebook_id)
                    or not isinstance(title, str) or not title.strip() or len(title) > 300 or notebook_id in seen):
                raise ValueError('Invalid notebook metadata')
            seen.add(notebook_id)
            notebooks.append({'id': notebook_id, 'title': title.strip()})
        return {'state': 'ok', 'notebooks': notebooks}
    except (ValueError, OSError, TypeError, AttributeError):
        return {'state': 'cli_error', 'notebooks': []}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--origin', required=True)
    parser.add_argument('--skip-cookie-login', action='store_true', help='Setup command already completed local login')
    parser.add_argument('--once', action='store_true', help='Report once and exit (diagnostics)')
    args = parser.parse_args()
    url = urllib.parse.urlsplit(args.origin)
    if (url.username or url.password or url.path not in ('', '/') or url.query or url.fragment
            or not url.hostname or (url.scheme != 'https' and not (url.scheme == 'http' and url.hostname in ('localhost', '127.0.0.1', '::1')))):
        parser.error('Origin must be HTTPS, or loopback HTTP for development')
    origin = args.origin.rstrip('/')
    print('AuthAPI NotebookLM bridge: notebook IDs/titles only; Google credentials stay local.', flush=True)
    if sys.stdin.isatty():
        import getpass
        token = getpass.getpass('One-time pairing code: ')
    else:
        token = sys.stdin.readline(128).strip()
    if not re.fullmatch(r'[\w-]{43}', token):
        parser.error('Invalid pairing code')
    paired = request(origin, 'redeem', {'token': token})
    token = None
    credential = paired['credential']
    browser = paired.get('browser', 'none')
    if browser != 'none' and not args.skip_cookie_login:
        if browser not in BROWSERS:
            raise ValueError('Unsupported explicitly selected browser')
        print('Importing local browser cookies with your selected browser: ' + browser, flush=True)
        try:
            code, _ = run_cli(['login', '--browser-cookies', browser], timeout=120)
            if code:
                raise RuntimeError('Cookie login failed. Install notebooklm-py[browser,cookies] with uv, verify the selected browser is signed in to Google NotebookLM, then generate a fresh website command and retry. CLI output was withheld to protect credentials.')
        except (OSError, ValueError):
            raise RuntimeError('Cookie login unavailable. Generate a fresh website setup command to install dependencies and retry, or select existing CLI login after running notebooklm login locally.') from None
    initial_report = list_notebooks()
    if initial_report['state'] != 'ok':
        request(origin, 'heartbeat', initial_report, credential)
        raise RuntimeError('Local notebook access failed (' + initial_report['state'] + '). Run notebooklm login locally, then generate a fresh website command and retry. No Google authentication output was uploaded.')
    print('Paired. Keep this terminal running. Ctrl-C disconnects the running bridge.', flush=True)
    try:
        while True:
            report = initial_report if initial_report is not None else list_notebooks()
            initial_report = None
            try:
                request(origin, 'heartbeat', report, credential)
                print('Reported: ' + report['state'] + ' (' + str(len(report['notebooks'])) + ' notebooks)', flush=True)
            except Revoked:
                raise
            except (OSError, ValueError, RuntimeError):
                print('Website temporarily unavailable; retrying. Status will become offline.', flush=True)
            if args.once:
                break
            time.sleep(30)  # Fixed polling, not a server-controlled command channel.
    except KeyboardInterrupt:
        try:
            request(origin, 'heartbeat', {'state': 'stopped', 'notebooks': []}, credential)
        except Exception:
            pass
        print('\nBridge stopped.', flush=True)


if __name__ == '__main__':
    try:
        main()
    except (Revoked, OSError, ValueError, RuntimeError) as error:
        print('Bridge failed: ' + str(error), file=sys.stderr)
        sys.exit(1)
