#!/usr/bin/env python3
"""One multiplexed WebSocket connection; session/recovery per protocol.md §2."""
import argparse
import asyncio
import json
import os
import sys
import time
from urllib.parse import urlsplit

from psf1 import Decoder, PSF1Error, SequenceBreak, State


async def session(ws, args):
    """Run one connection; every hello rebuilds descriptors and stream state."""
    decoder = state = None
    names = {}
    degraded = set()
    waiting = set()
    selected = listed = subscribed = False
    expirations = args.expiration if args.expiration is not None else "all"

    async def send(op, **values):
        await ws.send(json.dumps({"op": op, **values}))

    async def subscribe():
        nonlocal subscribed
        if selected and listed and not subscribed:
            await send("sub", underlying=args.underlying, expirations=expirations)
            subscribed = True

    async for raw in ws:
        try:
            message = decoder.decode(raw) if isinstance(raw, bytes) and decoder else (
                json.loads(raw) if isinstance(raw, str) else None)
            if message is None:
                raise PSF1Error("binary data before hello")
            kind = message.get("type")
            if kind == "hello":
                if message.get("version") != 1:
                    raise PSF1Error("unsupported session version")
                names.clear()
                decoder, state = Decoder(message), State(message)
                degraded.clear()
                waiting.clear()
                selected = listed = subscribed = False
                await send("format", format=args.format)
                await send("list", underlying=args.underlying)
            elif decoder is None:
                raise PSF1Error("expected hello first")
            elif kind == "format":
                if message.get("format") != args.format:
                    raise PSF1Error("unexpected selected format")
                selected = True
                await subscribe()
            elif kind == "streams" and message["underlying"] == args.underlying:
                names[message["underlying_iid"]] = message["underlying"]
                decoder.names.update(names)
                listed = True
                await subscribe()
            elif kind == "gap":
                s = message["stream"]
                degraded.add((s["underlying_iid"], s["expiration"]))
                print(json.dumps({"type": "degraded", "stream": s,
                                  "refetch": message.get("refetch")}), file=sys.stderr)
            elif kind == "error":
                # Only print codes; don't echo credentials or arbitrary server text.
                print(f"server error: {message.get('code', 'unknown')}", file=sys.stderr)
                if message.get("code") == "source_disconnected":
                    affected = message.get("streams")
                    if affected is None:
                        degraded.update(state.sequences)
                    else:
                        for s in affected:
                            for iid, name in names.items():
                                if s["underlying"] == name:
                                    degraded.add((iid, s["expiration"]))
                else:
                    # Reconnect to obtain new admission/leases or report denial again.
                    raise PSF1Error("server rejected request")
            elif kind == "frame":
                s = message["stream"]
                key = (s["underlying_iid"], s["expiration"])
                if key in waiting and not message["snapshot"]:
                    continue
                state.apply(message)
                if message["snapshot"]:
                    degraded.discard(key)
                    waiting.discard(key)
                print(json.dumps({"stream": s, "seq": message["seq"],
                                  "snapshot": message["snapshot"],
                                  "rows": {k: len(v) for k, v in message["records"].items()},
                                  "degraded": key in degraded}), flush=True)
            # Unknown control types are ignored (protocol §2).
        except SequenceBreak as exc:
            key = exc.stream
            decoder.drop(key)
            state.drop(key)
            if key not in waiting:
                underlying = names.get(key[0])
                if underlying is None:
                    raise PSF1Error("sequence break before catalog") from exc
                degraded.add(key)
                waiting.add(key)
                await send("unsub", underlying=underlying, expirations=[key[1]])
                await send("sub", underlying=underlying, expirations=[key[1]])


async def run(args, api_key):
    # Modern asyncio API; dependency belongs only to this example.
    from websockets.asyncio.client import connect
    from websockets.exceptions import WebSocketException

    delay = 1
    while True:
        started = time.monotonic()
        try:
            async with connect(args.url,
                               additional_headers={"Authorization": f"Bearer {api_key}"},
                               max_size=None) as ws:
                await session(ws, args)
        except (OSError, WebSocketException, PSF1Error, ValueError, KeyError) as exc:
            print(f"connection ended ({type(exc).__name__}); reconnecting", file=sys.stderr)
        if time.monotonic() - started >= 60:
            delay = 1
        await asyncio.sleep(delay)
        delay = min(30, delay * 2)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--url", default="wss://api.optionsdata.ai/v1/stream")
    parser.add_argument("--format", choices=("json", "psf1"), default="json")
    parser.add_argument("--underlying", required=True)
    parser.add_argument("--expiration", action="append",
                        help='repeat for multiple streams; "" selects underlying; default all')
    args = parser.parse_args()
    url = urlsplit(args.url)
    if url.scheme not in ("ws", "wss") or not url.hostname or url.query or url.username or url.password:
        parser.error("--url must be ws:// or wss:// without queries or credentials")
    api_key = os.environ.get("OPTIONSDATA_API_KEY")
    if not api_key:
        parser.error("set OPTIONSDATA_API_KEY in the environment")
    try:
        asyncio.run(run(args, api_key))
    except KeyboardInterrupt:
        pass


if __name__ == "__main__":
    main()
