#!/usr/bin/env python3
#
# wsdata: data source and renderer for the wallstreet widgets
#
# The pages wallstreet used to scrape (Yahoo Finance, WSJ, Reuters feeds)
# are gone or refuse non-browser clients.  This helper fetches market
# movers from the Nasdaq API and headlines and pictures from the RSS feeds
# listed in newsboat.urls, caches them for a short while so that several
# panes share one request, and renders them for the widgets.
#
#   wsdata table                     coloured quote table
#   wsdata movers up|down            one line of gainers / losers
#   wsdata headlines                 one headline per line
#   wsdata image                     path of a random downloaded picture
#   wsdata browse                    the quote table, interactive: click a row or
#                                    move with the arrow keys to select a stock,
#                                    "/" searches a stock and adds it to the watchlist
#   wsdata chart                     price chart of the selected stock, follows
#                                    the selection; 1-4 or a click change the span
#   wsdata logo                      logo of the selected stock, follows the selection
#   wsdata cachedir                  path of the private cache directory
#   wsdata demofeed                  write the demo feed, print its urls file
#
# With WALLSTREET_DEMO=1 nothing is fetched: quotes, headlines and the picture
# are invented (companies that do not exist), for screenshots, tests and
# machines without a network.
#   wsdata marquee COLOR DELAY TEXT  scroll TEXT once across the terminal
#
# Licensed under the Apache License, Version 2.0, like the rest of this
# package.  Python standard library only.

import datetime
import hashlib
import ipaddress
import json
import os
import random
import re
import select
import shutil
import socket
import stat
import struct
import subprocess
import sys
import tempfile
import termios
import time
import tty
import unicodedata
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
import zlib

UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/130.0 Safari/537.36")
MOVERS_URL = "https://api.nasdaq.com/api/marketmovers?assetclass=stocks"
HERE = os.path.dirname(os.path.abspath(__file__))
MAX_BYTES = 8 * 1024 * 1024
DEMO = os.environ.get("WALLSTREET_DEMO") == "1"

# Invented companies and headlines for the demo mode
DEMO_STOCKS = [
    ("NRDL", "Nordlicht Robotics AG", 184.20), ("HLXQ", "Helix Quantum Corp.", 412.75),
    ("PXLF", "Pixelforge Studios", 63.18), ("VNTA", "Ventara Energy Holdings", 97.40),
    ("ORBT", "Orbital Freight Systems", 251.06), ("KRYO", "Kryon Semiconductor", 733.90),
    ("MSHL", "Marshland Foods Inc.", 41.52), ("TLLR", "Tiller & Rowe Insurance", 128.33),
    ("SYNP", "Synapse Therapeutics", 19.87), ("BLKW", "Blackwater Shipping Co.", 76.05),
    ("AURM", "Aurum Digital Bank", 302.44), ("FJRD", "Fjord Wind Power ASA", 55.61),
    ("QNTM", "Quantum Lantern Labs", 8.42), ("GRVT", "Gravita Space Mining", 3.17),
    ("CDRX", "Cedar Rx Pharmacies", 147.29), ("LMNR", "Luminar Glassworks", 88.76),
    ("OTTR", "Otter Creek Software", 215.80), ("ZPHR", "Zephyr Airlines Group", 34.95),
    ("MRDN", "Meridian Rail Corp.", 166.12), ("PLMN", "Palomino Payments", 271.38),
]
DEMO_HEADLINES = [
    "Nordlicht Robotics opens second plant as warehouse orders double",
    "Helix Quantum says its 400-qubit machine ran for a full day",
    "Central bank holds rates, hints at a cut in spring",
    "Kryon Semiconductor slides after cautious outlook for memory chips",
    "Fjord Wind Power wins the largest offshore tender of the year",
    "Aurum Digital Bank passes ten million customers",
    "Orbital Freight books first profit since listing",
    "Shipping rates ease as Blackwater adds six vessels",
    "Marshland Foods recalls oat bars over labelling error",
    "Zephyr Airlines orders forty regional jets",
    "Palomino Payments to buy rival in all-share deal",
    "Meridian Rail completes electrification of its northern line",
    "Synapse Therapeutics jumps on trial results for migraine drug",
    "Luminar Glassworks cuts energy use by a third with new furnace",
    "Copper hits a two-year high on grid spending",
    "Otter Creek Software raises full-year guidance",
    "Tiller & Rowe sees storm claims below forecast",
    "Cedar Rx to open two hundred pharmacies in rural towns",
    "Gravita Space Mining delays probe launch to next quarter",
    "Quantum Lantern Labs explores sale after funding round stalls",
    "Ventara Energy to spin off its storage business",
    "Pixelforge Studios sells four million copies in launch week",
    "Retail sales rise for the fifth month in a row",
    "Factory output steady as export orders recover",
]


def demo_movers():
    """Invented quotes that drift a little every minute, same for all panes."""
    rnd = random.Random(int(time.time() // 60))
    rows_ = []
    for sym, name, base in DEMO_STOCKS:
        pct = rnd.gauss(0, 3.2)
        last = base * (1 + pct / 100)
        rows_.append({"symbol": sym, "name": name, "lastSalePrice": "$%.2f" % last,
                      "lastSaleChange": "%+.2f" % (last - base), "change": "%+.2f%%" % pct,
                      "deltaIndicator": "up" if pct >= 0 else "down", "_pct": pct})
    by = sorted(rows_, key=lambda r: r["_pct"])
    table = lambda rs: {"table": {"rows": [{k: v for k, v in r.items() if k != "_pct"}
                                            for r in rs]}}
    return {"MostActiveByDollarVolume": table(rows_[:10]),
            "Nasdaq100Movers": table(rows_[10:18]),
            "MostAdvanced": table([r for r in by[::-1] if r["_pct"] > 0][:8]),
            "MostDeclined": table([r for r in by if r["_pct"] < 0][:8])}


def term_size():
    """Size of the terminal, also when stdout is a pipe or a $(...) capture."""
    for fd in (2, 0, 1):
        try:
            return os.get_terminal_size(fd)
        except OSError:
            continue
    return shutil.get_terminal_size((80, 24))


def cache_dir():
    """A directory only this user can write to.  Not under /tmp: a shared
    temporary directory would let another local user plant a symlink."""
    base = os.environ.get("XDG_CACHE_HOME")
    if not base:
        home = os.path.expanduser("~")
        base = os.path.join(home, "Library", "Caches") if sys.platform == "darwin" \
            else os.path.join(home, ".cache")
    path = os.path.join(base, "wallstreet")
    os.makedirs(path, mode=0o700, exist_ok=True)
    st = os.lstat(path)
    if not stat.S_ISDIR(st.st_mode) or st.st_uid != os.getuid():
        raise SystemExit("wsdata: refusing to use cache directory %s" % path)
    if st.st_mode & 0o077:
        os.chmod(path, 0o700)
    return path


CACHE = cache_dir()

# Only plain web requests: no file://, ftp:// or anything else
OPENER = urllib.request.OpenerDirector()
for _h in (urllib.request.HTTPHandler, urllib.request.HTTPSHandler,
           urllib.request.HTTPDefaultErrorHandler,
           urllib.request.HTTPErrorProcessor):
    OPENER.add_handler(_h())


class _Redirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        check_url(newurl)
        return super().redirect_request(req, fp, code, msg, headers, newurl)


OPENER.add_handler(_Redirect())


def check_url(url):
    """Refuse anything that is not a web address of a public host.  Feed
    contents decide which pictures are fetched, so they are not trusted."""
    parts = urllib.parse.urlsplit(url)
    if parts.scheme not in ("http", "https") or not parts.hostname:
        raise ValueError("refusing URL %r" % url)
    for info in socket.getaddrinfo(parts.hostname, None):
        ip = ipaddress.ip_address(info[4][0].split("%")[0])
        if not ip.is_global:
            raise ValueError("refusing non-public host %r" % parts.hostname)
    return url


def clean(text):
    """Remote text without control characters, so that a feed or a company
    name cannot send escape sequences to the terminal."""
    return "".join(ch if unicodedata.category(ch)[0] != "C" else " "
                   for ch in str(text))
COLORS = {"red": 31, "green": 32, "yellow": 33, "blue": 34,
          "magenta": 35, "cyan": 36, "white": 37}


def fetch(url, timeout=15):
    req = urllib.request.Request(check_url(url), headers={
        "User-Agent": UA, "Accept": "application/json, text/xml, */*"})
    with OPENER.open(req, timeout=timeout) as r:
        data = r.read(MAX_BYTES + 1)
    if len(data) > MAX_BYTES:
        raise ValueError("response too large")
    return data


def cached(name, ttl, producer):
    """Return producer() as bytes, reusing a copy younger than ttl seconds.
    A stale copy is better than nothing when the network is down."""
    path = os.path.join(CACHE, name)
    try:
        if time.time() - os.path.getmtime(path) < ttl:
            with open(path, "rb") as f:
                return f.read()
    except OSError:
        pass
    try:
        data = producer()
        fd, tmp = tempfile.mkstemp(dir=CACHE, prefix=".tmp-")
        with os.fdopen(fd, "wb") as f:
            f.write(data)
        os.replace(tmp, path)
        return data
    except Exception:
        try:
            with open(path, "rb") as f:
                return f.read()
        except OSError:
            return b""


def movers():
    if DEMO:
        return demo_movers()
    raw = cached("movers.json", 55, lambda: fetch(MOVERS_URL))
    try:
        return json.loads(raw)["data"]["STOCKS"]
    except Exception:
        return {}


def rows(section):
    try:
        return [{k: clean(v) for k, v in r.items()}
                for r in movers()[section]["table"]["rows"]]
    except Exception:
        return []


def feed_urls():
    urls = []
    try:
        with open(os.path.join(HERE, "newsboat.urls")) as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith("#"):
                    urls.append(line.split()[0])
    except OSError:
        pass
    return urls


def feeds():
    """Parsed feeds as a list of (title, picture-url-or-None)."""
    if DEMO:
        return [[title, None] for title in DEMO_HEADLINES]

    def produce():
        items = []
        for url in feed_urls():
            try:
                root = ET.fromstring(fetch(url))
            except Exception:
                continue
            for item in root.iter("item"):
                title = clean(item.findtext("title") or "").strip()
                pic = None
                for el in item.iter():
                    u = el.attrib.get("url", "")
                    if re.match(r"https?://", u) and re.search(r"\.jpe?g(\?|$)", u):
                        pic = u
                        break
                if title:
                    items.append([title, pic])
        if not items:
            raise RuntimeError("no feed reachable")
        return json.dumps(items).encode()
    try:
        return json.loads(cached("feeds.json", 300, produce))
    except Exception:
        return []


def cmd_table():
    cols = term_size().columns
    sections = (("MOST ACTIVE", "MostActiveByDollarVolume"),
                ("INDEX MOVERS" if DEMO else "NASDAQ-100 MOVERS", "Nasdaq100Movers"),
                ("ADVANCERS", "MostAdvanced"),
                ("DECLINERS", "MostDeclined"))
    out = []
    for title, key in sections:
        data = rows(key)
        if not data:
            continue
        out.append("\033[1;33m%s\033[0m" % title)
        out.append("\033[90m%s\033[0m" % ("-" * (cols - 1)))
        name_w = max(8, cols - 42)
        for r in data:
            pct = r.get("change", "")
            try:
                pct = "%+.2f%%" % float(pct.replace("%", "").replace(",", ""))
            except ValueError:
                pass
            down = r.get("deltaIndicator") == "down" or pct.startswith("-")
            c = "31" if down else "32"
            out.append("\033[1;34m%-6s\033[0m %-*s \033[1;35m%10s\033[0m "
                       "\033[1;%sm%10s %9s\033[0m" % (
                           r.get("symbol", "")[:6], name_w,
                           r.get("name", "")[:name_w],
                           r.get("lastSalePrice", "").lstrip("$")[:10],
                           c, r.get("lastSaleChange", "")[:10], pct[:9]))
        out.append("")
    if not out:
        out = ["\033[33mNo market data available right now.\033[0m"]
    # Never print more than fits: the top of the table is what matters
    lines = term_size().lines
    out = out[:max(3, lines - 1)]
    # A section that lost all its rows to the cut would be a bare heading
    while len(out) > 3 and (out[-1] == "" or out[-1].startswith(("\033[90m", "\033[1;33m"))):
        out.pop()
    print("\n".join(out).rstrip("\n"))


def percent(row):
    """The row's change in percent as a number, or None."""
    try:
        return float(row.get("change", "").replace("%", "").replace(",", ""))
    except ValueError:
        return None


def cmd_movers(direction):
    """One line of gainers or losers: every symbol once, only the asked direction."""
    up = direction == "up"
    parts, seen = [], set()
    for r in rows("MostAdvanced" if up else "MostDeclined") + rows("Nasdaq100Movers"):
        pct, sym = percent(r), r.get("symbol", "")
        if pct is None or pct == 0 or (pct > 0) != up or sym in seen:
            continue
        seen.add(sym)
        parts.append("%s %s %+.2f%%" % (sym, r.get("lastSalePrice", "").lstrip("$"), pct))
    print(" ... ".join(parts))


def cmd_headlines():
    seen = set()
    for title, _ in feeds():
        if title not in seen:
            seen.add(title)
            print(title)


# ---------------------------------------------------------------- selection
#
# The quote table and the chart are two processes in two panes.  What is
# selected travels through one small file in the cache directory.

SPANS = (("1d", "1D"), ("1m", "1M"), ("3m", "3M"), ("ytd", "YTD"), ("1y", "1Y"))
SPAN_KEYS = [key for key, _ in SPANS]
OPEN, CLOSE = 9 * 60 + 30, 16 * 60       # the regular session in minutes of the New York day


def span_days(span, now=None):
    """How many days back a span reaches; 0 for the trading day."""
    now = time.time() if now is None else now
    if span == "ytd":
        # from the first trading day of the year, as chart sites count it; the change
        # is then measured against that day's close like in every other span
        return time.gmtime(now).tm_yday - 1
    return {"1d": 0, "1m": 31, "3m": 92, "1y": 366}[span]


def selection_path():
    return os.path.join(CACHE, "selection-demo.json" if DEMO else "selection.json")


def read_selection():
    try:
        with open(selection_path(), encoding="utf-8") as f:
            data = json.load(f)
        symbol = clean(data.get("symbol", ""))[:12]
        span = data.get("span")
        return (symbol if re.fullmatch(r"[A-Za-z0-9.^-]{1,12}", symbol) else "",
                span if span in SPAN_KEYS else "1d")
    except (OSError, ValueError, AttributeError):
        return "", "1d"


def write_selection(symbol=None, span=None):
    old_symbol, old_span = read_selection()
    data = {"symbol": old_symbol if symbol is None else symbol,
            "span": old_span if span is None else span}
    fd, tmp = tempfile.mkstemp(dir=CACHE, prefix=".tmp-")
    with os.fdopen(fd, "w", encoding="utf-8") as f:
        json.dump(data, f)
    os.replace(tmp, selection_path())


# ------------------------------------------------------------------ history

def demo_history(symbol, span):
    """An invented course that ends at the symbol's current demo quote."""
    row = next((r for key in ("MostActiveByDollarVolume", "Nasdaq100Movers")
                for r in rows(key) if r.get("symbol") == symbol), None)
    base = next((b for sym, _, b in DEMO_STOCKS if sym == symbol), 100.0)
    name = next((n for sym, n, _ in DEMO_STOCKS if sym == symbol), symbol)
    last = float(row["lastSalePrice"].lstrip("$")) if row else base
    days = span_days(span)
    n = 390 if span == "1d" else max(5, days * 252 // 366)
    start = base if span == "1d" else base * (1 - min(0.3, days / 1220.0))
    rnd = random.Random("%s/%s/%d" % (symbol, span, time.time() // 86400))
    walk, level = [], 0.0
    for _ in range(n):
        level += rnd.gauss(0, 1)
        walk.append(level)
    scale = max(abs(last - start), base * 0.012) / max(1e-9, max(abs(w) for w in walk)) * 0.9
    points = []
    for i, w in enumerate(walk):
        t = i / (n - 1)
        bridge = (w - walk[0] * (1 - t) - walk[-1] * t) * scale   # noise that is zero at both ends
        points.append(start + (last - start) * t + bridge)
    now = time.time()
    if span == "1d":
        labels = ("9:30 AM", "4:00 PM")
    else:
        labels = (time.strftime("%m/%d/%Y", time.localtime(now - days * 86400)),
                  time.strftime("%m/%d/%Y", time.localtime(now)))
    return {"symbol": symbol, "name": name, "points": points, "labels": labels,
            "last": last, "reference": base if span == "1d" else points[0],
            "reference_line": span == "1d", "dim_from": None, "extended": None}


# ------------------------------------------------------- stocks outside the US
#
# Nasdaq only knows what is listed on a US exchange.  Everything else - Volkswagen,
# Mercedes-Benz, Siemens - comes from Lang & Schwarz (ls-tc.de), a German exchange that
# trades some thousand stocks from 8:00 to 23:00 and quotes them in euro.  Such a stock
# is known here by its ISIN, which no ticker symbol can be mistaken for.

ISIN = re.compile(r"[A-Z]{2}[A-Z0-9]{9}[0-9]")
LS = "https://www.ls-tc.de/_rpc/json/"


def is_isin(symbol):
    return bool(ISIN.fullmatch(symbol or ""))


def ls_search(query):
    """What Lang & Schwarz finds for QUERY: [{"symbol" (the ISIN), "label" (the WKN),
    "name", "exchange", "id"}], stocks and funds only."""
    # the key keeps "mercedes benz" and "mercedes-benz" apart: they are answered differently
    key = "ls-search-%s.json" % hashlib.sha1(query.lower().encode()).hexdigest()[:20]
    url = LS + ".lstc/instrument/search/main?localeId=2&q=" + urllib.parse.quote(query, safe="")
    try:
        data = json.loads(cached(key, 3600, lambda: fetch(url)))
    except ValueError:
        return []
    out = []
    for item in data if isinstance(data, list) else []:
        try:
            isin = clean(item.get("isin") or "")
            if item.get("categorySymbol") not in ("STK", "ETF") or not is_isin(isin):
                continue
            out.append({"symbol": isin, "label": clean(item.get("wkn") or "")[:6],
                        "name": clean(item.get("displayname") or isin)[:80],
                        "exchange": "L&S EUR", "id": int(item["instrumentId"])})
        except (AttributeError, KeyError, TypeError, ValueError):
            continue
    return out


def ls_instrument(isin):
    """The entry of one ISIN at Lang & Schwarz, or None."""
    if not is_isin(isin):
        return None
    return next((r for r in ls_search(isin) if r["symbol"] == isin), None)


def label(symbol):
    """What stands in the narrow symbol column: the ticker, or the WKN of an ISIN."""
    if symbol in INDEX:
        return INDEX[symbol][0]
    if DEMO or not is_isin(symbol):
        return symbol
    found = ls_instrument(symbol)
    return (found and found["label"]) or symbol


def ls_series(isin, series, ttl):
    """([(milliseconds, price)], yesterday's close or None) of one ISIN; series is
    "intraday" (a point a minute) or "history" (a point a day)."""
    found = ls_instrument(isin)
    if not found:
        return [], None
    url = LS + "instrument/chart/dataForInstrument?instrumentId=%d&marketId=1&quotetype=mid&series=%s&localeId=2" % (
        found["id"], series)
    try:
        data = json.loads(cached("ls-%s-%s.json" % (series, isin), ttl, lambda: fetch(url)))
        points = [(int(t), float(v)) for t, v in data["series"][series]["data"] if v is not None]
        previous = next((float(l["value"]) for l in (data.get("info") or {}).get("plotlines") or []
                         if l.get("id") == "previousDay"), None)
    except (ValueError, KeyError, TypeError):
        return [], None
    return points, previous


def berlin(ms, fmt):
    """A moment as the exchange's clock shows it."""
    try:
        import zoneinfo
        zone = zoneinfo.ZoneInfo("Europe/Berlin")
    except Exception:                       # no zone data on this machine: Central European Time
        zone = datetime.timezone(datetime.timedelta(hours=1))
    return datetime.datetime.fromtimestamp(ms / 1000, zone).strftime(fmt)


def ls_quote(isin):
    points, previous = ls_series(isin, "intraday", 60)
    if not points:
        return None
    last = points[-1][1]
    change = last - previous if previous else 0.0
    return {"last": last, "change": change, "pct": change / previous * 100 if previous else 0.0,
            "extended": None, "currency": "EUR"}


def ls_history(isin, span):
    found = ls_instrument(isin)
    if not found:
        return None
    base = {"symbol": isin, "name": found["name"], "dim_from": None, "extended": None, "currency": "EUR"}
    if span == "1d":
        points, previous = ls_series(isin, "intraday", 60)
        if len(points) < 2:
            return None
        return dict(base, points=[v for _, v in points], last=points[-1][1], reference=previous,
                    reference_line=previous is not None,
                    labels=(berlin(points[0][0], "%H:%M"), berlin(points[-1][0], "%H:%M")))
    days, _ = ls_series(isin, "history", 3600)
    start = (time.time() - span_days(span) * 86400) * 1000
    days = [(t, v) for t, v in days if t >= start]
    q = ls_quote(isin)
    if q and days and berlin(days[-1][0], "%Y%m%d") == berlin(time.time() * 1000, "%Y%m%d"):
        days[-1] = (days[-1][0], q["last"])            # today's point follows the day
    elif q and days:
        days.append((int(time.time() * 1000), q["last"]))
    if len(days) < 2:
        return None
    return dict(base, points=[v for _, v in days], last=days[-1][1], reference=days[0][1], reference_line=False,
                labels=(berlin(days[0][0], "%m/%d/%Y"), berlin(days[-1][0], "%m/%d/%Y")))


# ------------------------------------------------------------------ indices
#
# An index is not traded, so neither exchange above has it.  ING publishes the course of
# the large ones for its customers' charts: an indication from 8:00 to 22:00 Berlin time,
# also while the index's own exchange is closed.  Like the stocks from Lang & Schwarz an
# index is known here by its ISIN; the table shows the short name.

INDICES = (("US78378X1072", "SPX", "S&P 500", "sp500 s&p500 standard poors"),
           ("US2605661048", "DJI", "Dow Jones", "dow30 djia industrial"),
           ("US6311011026", "NDX", "NASDAQ 100", "nasdaq100 ndx"),
           ("DE0008469008", "DAX", "Deutscher Aktienindex", "dax40"),
           ("EU0009658145", "SX5E", "EURO STOXX 50", "eurostoxx stoxx50 estx50"),
           ("DE0008467416", "MDAX", "Mid-Cap-DAX", ""),
           ("DE0007203275", "TECDAX", "Technologie-DAX", ""),
           ("DE0009653386", "SDAX", "Small-Cap-DAX", ""),
           ("FR0003500008", "CAC", "CAC 40", "cac40 paris"),
           ("CH0009980894", "SMI", "Swiss Market Index", "schweiz"),
           ("JP9010C00002", "N225", "Nikkei 225", "nikkei225 japan tokio"),
           ("HK0000004322", "HSI", "Hang Seng", "hangseng hongkong"))
INDEX = {isin: (short, name) for isin, short, name, _ in INDICES}
INDEX_ROWS = 5           # how many of them stand in the table; the others are found by the search
ING = "https://component-api.wertpapiere.ing.de/api/v1/charts/shm/%s?timeRange=%s"


def is_index(symbol):
    return symbol in INDEX


def index_search(query):
    """The indices QUERY names: by the beginning of a word of the name, the short name or
    a by-name, or - from three characters - by any part of name or short name."""
    squash = lambda text: re.sub(r"[^a-z0-9]", "", text.lower())
    q = squash(query)
    if len(q) < 2:
        return []
    out = []
    for isin, short, name, more in INDICES:
        words = [squash(w) for w in (name + " " + short + " " + more).replace("-", " ").split()]
        whole = (squash(name), squash(short))
        if any(w.startswith(q) for w in words + list(whole)) or (len(q) >= 3 and any(q in w for w in whole)):
            out.append({"symbol": isin, "label": short, "name": name, "exchange": "INDEX"})
    return out


def ing_series(isin, span, ttl):
    """[(milliseconds, value)] of one index; span is "Intraday" or "OneYear"."""
    try:
        data = json.loads(cached("ing-%s-%s.json" % (span, isin), ttl, lambda: fetch(ING % (isin, span))))
        return [(int(t), float(v)) for t, v in data["instruments"][0]["data"] if v is not None]
    except (ValueError, KeyError, TypeError, IndexError):
        return []


def index_day(isin):
    """(the day's points, the close of the day before or None)."""
    points = ing_series(isin, "Intraday", 60)
    if not points:
        return [], None
    day = berlin(points[0][0], "%Y%m%d")
    before = [v for t, v in ing_series(isin, "OneYear", 3600) if berlin(t, "%Y%m%d") < day]
    return points, (before[-1] if before else None)


def index_quote(isin):
    points, previous = index_day(isin)
    if not points:
        return None
    last = points[-1][1]
    change = last - previous if previous else 0.0
    return {"last": last, "change": change, "pct": change / previous * 100 if previous else 0.0, "extended": None}


def index_history(isin, span):
    short, name = INDEX[isin]
    base = {"symbol": short, "name": name, "dim_from": None, "extended": None}
    points, previous = index_day(isin)
    if span == "1d":
        if len(points) < 2:
            return None
        return dict(base, points=[v for _, v in points], last=points[-1][1], reference=previous,
                    reference_line=previous is not None,
                    labels=(berlin(points[0][0], "%H:%M"), berlin(points[-1][0], "%H:%M")))
    start = (time.time() - span_days(span) * 86400) * 1000
    days = [(t, v) for t, v in ing_series(isin, "OneYear", 3600) if t >= start]
    if points and days and berlin(days[-1][0], "%Y%m%d") >= berlin(points[0][0], "%Y%m%d"):
        days[-1] = (days[-1][0], points[-1][1])        # the day's bar follows the day
    elif points and days:
        days.append(points[-1])
    if len(days) < 2:
        return None
    return dict(base, points=[v for _, v in days], last=days[-1][1], reference=days[0][1], reference_line=False,
                labels=(berlin(days[0][0], "%m/%d/%Y"), berlin(days[-1][0], "%m/%d/%Y")))


def index_rows():
    """The first indices as table rows; an index without an answer is left out."""
    out = []
    for isin, short, name, _ in INDICES[:INDEX_ROWS]:
        q = None if DEMO else index_quote(isin)
        if q:
            out.append({"symbol": isin, "label": short, "name": name, "lastSalePrice": price(q["last"]),
                        "lastSaleChange": "%+.2f" % q["change"], "change": "%+.2f%%" % q["pct"],
                        "deltaIndicator": "down" if q["change"] < 0 else "up"})
    return out


def number(value):
    """A price or a change as the API writes it: "$1,010.50", "-6.71", "-4.12%"."""
    return float(str(value).replace("$", "").replace(",", "").replace("%", ""))


def nasdaq(symbol, what, name, ttl, query=""):
    """The "data" part of one Nasdaq answer for a symbol; a stock first, then an ETF."""
    for asset in ("stocks", "etf"):
        url = "https://api.nasdaq.com/api/quote/%s/%s?assetclass=%s%s" % (
            urllib.parse.quote(symbol, safe=""), what, asset, query)
        raw = cached("%s-%s-%s.json" % (name, re.sub(r"[^A-Za-z0-9]", "_", symbol), asset),
                     ttl, lambda: fetch(url))
        try:
            data = json.loads(raw)["data"]
        except (ValueError, KeyError, TypeError):
            continue
        if data and (what != "chart" or data.get("chart")):
            ASSET[symbol] = asset
            return data
    return None


ASSET = {}           # symbol -> "stocks" or "etf", as far as Nasdaq has answered for it


def is_etf(symbol):
    """Whether Nasdaq keeps this symbol as a fund."""
    if symbol not in ASSET and not is_isin(symbol):
        nasdaq(symbol, "info", "info", 60)
    return ASSET.get(symbol) == "etf"


def quote(symbol):
    """The day's official quote and, outside the session, the extended-hours one.

    {"last", "change", "pct"} plus "extended": None or {"label", "last", "change", "pct"}.
    After the close Nasdaq moves the session's figures into "secondaryData" and reports the
    after-hours trade as the primary one - which is why the chart must not take the newest
    price for the day's result.
    """
    if is_index(symbol):
        return index_quote(symbol)
    if is_isin(symbol):
        return ls_quote(symbol)
    data = nasdaq(symbol, "info", "info", 60)
    try:
        def part(block):
            return {"last": number(block["lastSalePrice"]), "change": number(block["netChange"]),
                    "pct": number(block["percentageChange"])}
        primary = part(data["primaryData"])
        secondary = data.get("secondaryData")
        if secondary and secondary.get("lastSalePrice"):
            official = part(secondary)
            official["extended"] = dict(primary, label=clean(data.get("marketStatus") or "extended")[:14].lower())
            return official
        primary["extended"] = None
        return primary
    except (KeyError, TypeError, ValueError):
        return None


def minute_of_day(point):
    """Minutes since midnight in New York; the API writes local time as if it were UTC."""
    t = time.gmtime(point["x"] / 1000)
    return t.tm_hour * 60 + t.tm_min


def day_history(symbol, data):
    """The trading day: the regular session, with after-hours trading behind it."""
    chart = [p for p in data["chart"] if "x" in p and "y" in p]
    session = [p for p in chart if OPEN <= minute_of_day(p) <= CLOSE]
    after = [p for p in chart if minute_of_day(p) > CLOSE]
    if session:
        shown, dim_from = session + after, (len(session) if after else None)
    else:
        shown, dim_from = chart, 0             # before the opening bell there is only pre-market
    if len(shown) < 2:
        return None
    points = [float(p["y"]) for p in shown]
    q = quote(symbol)
    if q:
        last, reference, extended = q["last"], q["last"] - q["change"], q["extended"]
    else:                                      # no quote: show the course without a verdict
        last, reference, extended = points[(dim_from or len(points)) - 1], None, None
    return {"symbol": symbol, "name": clean(data.get("company") or symbol), "points": points,
            "labels": (clean(shown[0]["z"]["dateTime"]), clean(shown[-1]["z"]["dateTime"])),
            "last": last, "reference": reference, "reference_line": reference is not None,
            "dim_from": dim_from, "extended": extended}


def history(symbol, span):
    """Course of one symbol for a span, or None.

    {symbol, name, points, labels, last, reference, reference_line, dim_from, extended}:
    reference is what the change is measured against (None: unknown), dim_from the index
    of the first point outside the regular session.
    """
    if DEMO:
        return demo_history(symbol, span)
    if is_index(symbol):
        return index_history(symbol, span)
    if is_isin(symbol):
        return ls_history(symbol, span)
    try:
        if span == "1d":
            data = nasdaq(symbol, "chart", "chart-1d", 60)
            return day_history(symbol, data) if data else None
        day = lambda t: time.strftime("%Y-%m-%d", time.gmtime(t))
        now = time.time()
        data = nasdaq(symbol, "chart", "chart-" + span, 3600,
                      "&fromdate=%s&todate=%s" % (day(now - span_days(span) * 86400), day(now)))
        if not data:
            return None
        points = [float(p["y"]) for p in data["chart"]]
        labels = [clean(data["chart"][0]["z"]["dateTime"]), clean(data["chart"][-1]["z"]["dateTime"])]
        last = points[-1]
        q = quote(symbol)
        today = time.strftime("%m/%d/%Y", time.gmtime(now - 5 * 3600))
        if q and labels[1] != today:
            # the daily closes end with yesterday: today's price belongs at the right edge
            points.append(q["last"])
            labels[1], last = today, q["last"]
        elif q:
            last = q["last"]
    except (KeyError, TypeError, ValueError, IndexError):
        return None
    if len(points) < 2:
        return None
    return {"symbol": symbol, "name": clean(data.get("company") or symbol), "points": points,
            "labels": tuple(labels), "last": last, "reference": points[0],
            "reference_line": False, "dim_from": None, "extended": None}


# -------------------------------------------------------------------- chart

BRAILLE = ((0x01, 0x08), (0x02, 0x10), (0x04, 0x20), (0x40, 0x80))   # [row][column] of a cell


def plot(points, width, height, low=None, high=None):
    """The course as HEIGHT strings of WIDTH braille characters (2x4 dots per cell).

    LOW and HIGH widen the value range, for a reference line outside the course."""
    dots_w, dots_h = width * 2, height * 4
    low = min(points) if low is None else min(low, min(points))
    high = max(points) if high is None else max(high, max(points))
    spread = (high - low) or 1.0
    ys = []
    for x in range(dots_w):
        # straight lines between the points: 22 daily closes on 180 dots would be stairs
        at = x * (len(points) - 1) / max(1, dots_w - 1)
        i = min(len(points) - 2, int(at))
        value = points[i] + (points[i + 1] - points[i]) * (at - i)
        ys.append(int(round((high - value) / spread * (dots_h - 1))))
    cells = [[0] * width for _ in range(height)]
    for x, y in enumerate(ys):
        prev = ys[x - 1] if x else y
        for dot in range(min(prev, y), max(prev, y) + 1):      # close the gaps of steep moves
            cells[dot // 4][x // 2] |= BRAILLE[dot % 4][x % 2]
    return ["".join(chr(0x2800 + c) if c else " " for c in line) for line in cells]


def price(value):
    return "%.2f" % value if abs(value) < 100000 else "%.0f" % value


TAB_ROW = 3            # the line of the chart pane that holds the span tabs, 1-based
TAB_GAP = 2


def tab_cells():
    """Per span the 1-based columns of its tab, as drawn by chart_lines."""
    cells, x = {}, 1
    for key, label in SPANS:
        cells[key] = range(x, x + len(label) + 2)
        x += len(label) + 2 + TAB_GAP
    return cells


def tab_at(x, y):
    """The span whose tab is at cell (x, y) of the chart pane, or None."""
    if y != TAB_ROW:
        return None
    return next((key for key, cells in tab_cells().items() if x in cells), None)


def chart_lines(data, span, cols, lines):
    """The chart pane as a list of at most LINES strings no wider than COLS - 1."""
    width = max(20, cols - 1)
    tabs = (" " * TAB_GAP).join(("\033[7m %s \033[27m" if key == span else " %s ") % label
                                for key, label in SPANS)
    out = []
    if not data:
        symbol = read_selection()[0]
        out.append("\033[1;34m%s\033[0m" % symbol if symbol else "\033[1;33mCHART\033[0m")
        out.append("")                     # keeps the tabs on TAB_ROW, where a click looks for them
        out.append("\033[90m%s\033[0m" % tabs)
        out.append("")
        out.append("\033[33m%s\033[0m" % (
            "No chart data for this symbol right now." if symbol
            else "Select a stock: click a row or use the arrow keys.")[:width])
        return out[:lines]
    reference = data.get("reference")
    change = data["last"] - reference if reference is not None else 0.0
    colour = "32" if change >= 0 else "31"
    name_w = max(0, width - len(data["symbol"]) - 1)
    out.append("\033[1;34m%s\033[0m %s" % (data["symbol"], data["name"][:name_w]))
    shown = price(data["last"]) + (" " + data["currency"] if data.get("currency") else "")
    head, plain = "\033[1;35m%s\033[0m" % shown, shown
    if reference:
        text = " %+.2f  %+.2f%%" % (change, change / reference * 100)
        head, plain = head + "\033[1;%sm%s\033[0m" % (colour, text), plain + text
    extended = data.get("extended")
    if extended:
        text = "  %s %s %+.2f (%+.2f%%)" % (extended["label"], price(extended["last"]),
                                            extended["change"], extended["pct"])
        if len(plain) + len(text) <= width:
            head += "\033[90m%s\033[0m" % text
    out.append(head)
    out.append("\033[90m%s\033[0m" % tabs)
    height = lines - 5
    points = data["points"]
    marked = reference if data.get("reference_line") and reference is not None else None
    low = min(points) if marked is None else min(marked, min(points))
    high = max(points) if marked is None else max(marked, max(points))
    axis = max(len(price(low)), len(price(high))) + 1
    plot_w = width - axis
    if height < 3 or plot_w < 10:
        return out[:lines]
    # the session in the colour of the day's result, trading outside it in grey
    dim_from = data.get("dim_from")
    dim_col = plot_w if dim_from is None else int(dim_from * plot_w / len(points))
    mark_row = None
    if marked is not None:
        mark_row = int(round((high - marked) / ((high - low) or 1.0) * (height * 4 - 1))) // 4
    labels = {0: price(high), height - 1: price(low), height // 2: price((high + low) / 2)}
    if mark_row is not None:
        # the reference takes the place of a neighbouring label instead of crowding it
        for row in (mark_row - 1, mark_row + 1):
            if row in labels and row not in (0, height - 1):
                del labels[row]
        labels[mark_row] = price(marked)
    for i, row in enumerate(plot(points, plot_w, height, low, high)):
        session, rest = row[:dim_col], row[dim_col:]
        if i == mark_row:
            # previous close: a dotted grey line wherever the course leaves room
            dotted = lambda part, c: "".join(
                "\033[90m\u2508\033[%sm" % c if ch == " " else ch for ch in part)
            session, rest = dotted(session, colour), dotted(rest, "90")
        out.append("\033[%sm%s\033[90m%s%*s\033[0m" % (colour, session, rest, axis, labels.get(i, "")))
    left, right = data["labels"]
    gap = max(1, plot_w - len(left) - len(right))
    out.append("\033[90m%s%s%s\033[0m" % (left, " " * gap, right)[:width + 9])
    return out[:lines]


# --------------------------------------------------------------------- logo
#
# The pane beside the feed reader shows the logo of the selected company on a
# light tile, drawn with half-block characters: every cell is two pixels, one
# above the other, so a 100 x 100 picture survives as something one recognises.

LOGO_URLS = ("https://assets.parqet.com/logos/symbol/%s?format=png&size=512",     # 512 px a side
             "https://financialmodelingprep.com/image-stock/%s.png")               # 100-250 px
LOGO_ISIN_URL = "https://assets.parqet.com/logos/isin/%s?format=png&size=512"    # stocks known by ISIN
TILE = (236, 238, 242)
TILE_DARK = (30, 32, 42)      # for a logo drawn in white
FONT = {  # 5 x 7, for the monogram of a company without a logo
    "A": "01110 10001 10001 11111 10001 10001 10001", "B": "11110 10001 10001 11110 10001 10001 11110",
    "C": "01110 10001 10000 10000 10000 10001 01110", "D": "11110 10001 10001 10001 10001 10001 11110",
    "E": "11111 10000 10000 11110 10000 10000 11111", "F": "11111 10000 10000 11110 10000 10000 10000",
    "G": "01110 10001 10000 10111 10001 10001 01111", "H": "10001 10001 10001 11111 10001 10001 10001",
    "I": "01110 00100 00100 00100 00100 00100 01110", "J": "00111 00010 00010 00010 00010 10010 01100",
    "K": "10001 10010 10100 11000 10100 10010 10001", "L": "10000 10000 10000 10000 10000 10000 11111",
    "M": "10001 11011 10101 10101 10001 10001 10001", "N": "10001 11001 10101 10011 10001 10001 10001",
    "O": "01110 10001 10001 10001 10001 10001 01110", "P": "11110 10001 10001 11110 10000 10000 10000",
    "Q": "01110 10001 10001 10001 10101 10010 01101", "R": "11110 10001 10001 11110 10100 10010 10001",
    "S": "01111 10000 10000 01110 00001 00001 11110", "T": "11111 00100 00100 00100 00100 00100 00100",
    "U": "10001 10001 10001 10001 10001 10001 01110", "V": "10001 10001 10001 10001 10001 01010 00100",
    "W": "10001 10001 10001 10101 10101 11011 10001", "X": "10001 10001 01010 00100 01010 10001 10001",
    "Y": "10001 10001 01010 00100 00100 00100 00100", "Z": "11111 00001 00010 00100 01000 10000 11111",
}


def png_pixels(data, limit=1024):
    """Decode a PNG into (width, height, rows of (r, g, b, a)).  Standard library only;
    up to 8 bits a channel, not interlaced - which is what logos are.  Anything else
    raises ValueError."""
    if data[:8] != b"\x89PNG\r\n\x1a\n":
        raise ValueError("not a PNG")
    pos, idat, palette, alpha, head = 8, [], None, b"", None
    while pos + 8 <= len(data):
        length, kind = struct.unpack(">I4s", data[pos:pos + 8])
        chunk = data[pos + 8:pos + 8 + length]
        pos += 12 + length
        if kind == b"IHDR":
            head = struct.unpack(">IIBBBBB", chunk)
        elif kind == b"PLTE":
            palette = chunk
        elif kind == b"tRNS":
            alpha = chunk
        elif kind == b"IDAT":
            idat.append(chunk)
        elif kind == b"IEND":
            break
    if not head:
        raise ValueError("no header")
    width, height, depth, colour, _, _, interlace = head
    channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(colour)
    packed = depth in (1, 2, 4) and colour in (0, 3)       # several pixels in one byte
    if not (depth == 8 or packed) or interlace or not channels \
            or not (0 < width <= limit and 0 < height <= limit):
        raise ValueError("unsupported PNG")
    stride = (width * channels * depth + 7) // 8
    unpack = zlib.decompressobj()
    raw = unpack.decompress(b"".join(idat), (stride + 1) * height)
    if len(raw) < (stride + 1) * height:
        raise ValueError("short PNG")
    rows, prev = [], bytearray(stride)
    for y in range(height):
        kind = raw[y * (stride + 1)]
        line = bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)])
        for i in range(stride):
            left = line[i - channels] if i >= channels else 0
            up = prev[i]
            corner = prev[i - channels] if i >= channels else 0
            if kind == 1:
                line[i] = (line[i] + left) & 255
            elif kind == 2:
                line[i] = (line[i] + up) & 255
            elif kind == 3:
                line[i] = (line[i] + (left + up) // 2) & 255
            elif kind == 4:
                guess = left + up - corner
                a, b, c = abs(guess - left), abs(guess - up), abs(guess - corner)
                line[i] = (line[i] + (left if a <= b and a <= c else up if b <= c else corner)) & 255
        prev = line
        if packed:
            # unpack to one byte a pixel; greys are spread over 0-255
            mask, spread = (1 << depth) - 1, (255 // ((1 << depth) - 1) if colour == 0 else 1)
            line = bytearray(((line[(x * depth) // 8] >> (8 - depth - (x * depth) % 8)) & mask) * spread
                             for x in range(width))
        row = []
        for x in range(width):
            px = line[x * channels:(x + 1) * channels]
            if colour == 6:
                row.append(tuple(px))
            elif colour == 2:
                row.append((px[0], px[1], px[2], 255))
            elif colour == 0:
                row.append((px[0], px[0], px[0], 255))
            elif colour == 4:
                row.append((px[0], px[0], px[0], px[1]))
            else:
                i = px[0]
                if not palette or i * 3 + 2 >= len(palette):
                    raise ValueError("bad palette")
                row.append((palette[i * 3], palette[i * 3 + 1], palette[i * 3 + 2],
                            alpha[i] if i < len(alpha) else 255))
        rows.append(row)
    return width, height, rows


def tile(image, size, margin=2):
    """The picture, scaled into a SIZE x SIZE tile of (r, g, b) on the tile's ground."""
    width, height, rows = image
    # a logo made for dark pages would vanish on the light tile: look at what it is drawn in
    light = weight = 0
    for row in rows[::max(1, height // 32)]:
        for r, g, b, a in row[::max(1, width // 32)]:
            light, weight = light + (299 * r + 587 * g + 114 * b) // 1000 * a, weight + a
    # ... unless it brings a ground of its own (opaque corners)
    framed = min(rows[0][0][3], rows[0][-1][3], rows[-1][0][3], rows[-1][-1][3]) > 200
    ground = TILE_DARK if weight and light / weight > 200 and not framed else TILE
    inner = max(1, size - 2 * margin)
    scale = max(width, height) / float(inner)
    out_w, out_h = max(1, int(round(width / scale))), max(1, int(round(height / scale)))
    grid = [[ground] * size for _ in range(size)]
    off_x, off_y = (size - out_w) // 2, (size - out_h) // 2
    if scale < 1:
        # enlarging: blend the four neighbours, or a small logo becomes a mosaic
        for y in range(out_h):
            fy = min(height - 1.0, max(0.0, (y + 0.5) * scale - 0.5))
            y0 = int(fy); y1 = min(height - 1, y0 + 1); wy = fy - y0
            for x in range(out_w):
                fx = min(width - 1.0, max(0.0, (x + 0.5) * scale - 0.5))
                x0 = int(fx); x1 = min(width - 1, x0 + 1); wx = fx - x0
                r = g = b = a = 0.0
                for (pr, pg, pb, pa), wgt in ((rows[y0][x0], (1 - wx) * (1 - wy)), (rows[y0][x1], wx * (1 - wy)),
                                               (rows[y1][x0], (1 - wx) * wy), (rows[y1][x1], wx * wy)):
                    r, g, b, a = r + pr * pa * wgt, g + pg * pa * wgt, b + pb * pa * wgt, a + pa * wgt
                cover = a / 255.0
                grid[off_y + y][off_x + x] = tuple(
                    int(round((c / a if a else 0) * cover + gr * (1 - cover))) for c, gr in zip((r, g, b), ground))
        return grid
    for y in range(out_h):
        for x in range(out_w):
            # average over the block of source pixels this pixel stands for
            x0, x1 = int(x * scale), max(int(x * scale) + 1, min(width, int((x + 1) * scale)))
            y0, y1 = int(y * scale), max(int(y * scale) + 1, min(height, int((y + 1) * scale)))
            r = g = b = a = n = 0
            for sy in range(y0, min(y1, height)):
                for sx in range(x0, min(x1, width)):
                    pr, pg, pb, pa = rows[sy][sx]
                    r, g, b, a, n = r + pr * pa, g + pg * pa, b + pb * pa, a + pa, n + 1
            if not n:
                continue
            cover = a / (255.0 * n)
            mix = lambda c, ground: int(round((c / a if a else 0) * cover + ground * (1 - cover)))
            grid[off_y + y][off_x + x] = (mix(r, ground[0]), mix(g, ground[1]), mix(b, ground[2]))
    return grid


def monogram(symbol, size):
    """A tile with the first two letters of the symbol, in a colour of its own."""
    letters = [c for c in symbol.upper() if c in FONT][:2] or ["X"]
    hue = zlib.crc32(symbol.encode()) % 360
    # one of twelve calm colours; the letters in white
    c, x = 0.55, 0.55 * (1 - abs((hue / 60.0) % 2 - 1))
    r, g, b = [(c, x, 0), (x, c, 0), (0, c, x), (0, x, c), (x, 0, c), (c, 0, x)][hue // 60]
    ground = tuple(int((v + 0.18) * 255) for v in (r, g, b))
    scale = max(1, (size - 4) // (len(letters) * 6 - 1))
    text_w, text_h = (len(letters) * 6 - 1) * scale, 7 * scale
    grid = [[ground] * size for _ in range(size)]
    off_x, off_y = (size - text_w) // 2, (size - text_h) // 2
    for n, letter in enumerate(letters):
        for gy, bits in enumerate(FONT[letter].split()):
            for gx, bit in enumerate(bits):
                if bit == "1":
                    for dy in range(scale):
                        for dx in range(scale):
                            py, px = off_y + gy * scale + dy, off_x + (n * 6 + gx) * scale + dx
                            if 0 <= py < size and 0 <= px < size:
                                grid[py][px] = (255, 255, 255)
    return grid


NO_LOGO = set()      # symbols neither source had a picture for, so each is asked once


GRIDS = {}           # (symbol, size) -> tile: decoding and scaling 512 px takes a moment


def logo_grid(symbol, size):
    """The company's logo as a tile, or its monogram if there is none to be had."""
    if (symbol, size) not in GRIDS:
        if len(GRIDS) > 24:
            GRIDS.clear()
        GRIDS[(symbol, size)] = _logo_grid(symbol, size)
    return GRIDS[(symbol, size)]


def _logo_grid(symbol, size):
    if not DEMO and SYMBOL.fullmatch(symbol or "") and symbol not in NO_LOGO:
        # a fund is known by the name of its family ("SPDR", "Vanguard"), and that is what
        # the second source draws; the first shows the issuer's mark, which nobody knows
        urls = (LOGO_ISIN_URL,) if is_isin(symbol) else LOGO_URLS[::-1] if is_etf(symbol) else LOGO_URLS
        for n, url in enumerate(urls):
            name = "logo-%s-%s.png" % (urllib.parse.urlsplit(url).hostname, re.sub(r"[^A-Za-z0-9]", "_", symbol))
            data = cached(name, 30 * 86400, lambda: fetch(url % urllib.parse.quote(symbol, safe=""), timeout=6))
            try:
                return tile(png_pixels(data), size)
            except (ValueError, struct.error, zlib.error, IndexError):
                try:
                    os.unlink(os.path.join(CACHE, name))    # not a picture: do not keep it
                except OSError:
                    pass
        NO_LOGO.add(symbol)
    return monogram(label(symbol) if symbol else "?", size)


def colour256(rgb):
    """The nearest of the 216 cube colours and 24 greys every terminal has."""
    r, g, b = rgb
    if max(r, g, b) - min(r, g, b) < 12:
        grey = (r + g + b) // 3
        return 16 if grey < 5 else 231 if grey > 246 else 232 + min(23, (grey - 8) // 10)
    step = lambda v: 0 if v < 48 else 1 if v < 115 else (v - 35) // 40
    return 16 + 36 * step(r) + 6 * step(g) + step(b)


def logo_lines(symbol, cols, lines, rgb=False):
    """The logo pane in characters: the tile, centred, and the symbol below it."""
    size = max(8, min(cols - 2, (lines - 2) * 2) // 2 * 2)
    grid = logo_grid(symbol, size)
    pad = " " * max(0, (cols - 1 - size) // 2)
    out = [""] * max(0, (lines - 2 - size // 2) // 2)
    for y in range(0, size, 2):
        row, last = [], None
        for x in range(size):
            if rgb:
                pair = grid[y][x] + grid[y + 1][x]
            else:
                pair = (colour256(grid[y][x]), colour256(grid[y + 1][x]))
            if pair != last:
                row.append(("\033[38;2;%d;%d;%d;48;2;%d;%d;%dm" if rgb else "\033[38;5;%d;48;5;%dm") % pair)
                last = pair
            row.append("▀")                   # upper half block: top pixel fg, bottom pixel bg
        out.append(pad + "".join(row) + "\033[0m")
    out.append("")
    out.append(logo_caption(symbol, cols))
    return out[:lines]


def logo_caption(symbol, cols):
    symbol = label(symbol)
    return "\033[1;34m%s\033[0m" % (" " * max(0, (cols - 1 - len(symbol)) // 2) + symbol)


def sixel(grid):
    """The tile as a sixel picture: real pixels, for terminals that draw them."""
    height, width = len(grid), len(grid[0])
    # at most 255 colours: 5 bits a channel, and the rarest go to their nearest neighbour
    key = lambda px: (px[0] >> 3, px[1] >> 3, px[2] >> 3)
    count = {}
    for row in grid:
        for px in row:
            k = key(px)
            count[k] = count.get(k, 0) + 1
    kept = sorted(count, key=count.get, reverse=True)[:255]
    index = {k: n for n, k in enumerate(kept)}
    for k in count:
        if k not in index:
            index[k] = index[min(kept, key=lambda c: sum((a - b) ** 2 for a, b in zip(c, k)))]
    out = ['\033P0;1;0q"1;1;%d;%d' % (width, height)]
    for k, n in ((k, index[k]) for k in kept):
        out.append("#%d;2;%d;%d;%d" % ((n,) + tuple((c * 8 + 4) * 100 // 255 for c in k)))
    for top in range(0, height, 6):
        bands = {}
        for bit, row in enumerate(grid[top:top + 6]):
            for x, px in enumerate(row):
                n = index[key(px)]
                line = bands.get(n)
                if line is None:
                    line = bands[n] = [0] * width
                line[x] |= 1 << bit
        parts = []
        for n, line in bands.items():
            run, cells = None, []
            for v in line + [None]:
                if run and v == run[0]:
                    run[1] += 1
                    continue
                if run:
                    ch = chr(63 + run[0])
                    cells.append(ch * run[1] if run[1] < 4 else "!%d%s" % (run[1], ch))
                run = [v, 1]
            parts.append("#%d%s" % (n, "".join(cells)))
        out.append("$".join(parts) + "-")
    out.append("\033\\")
    return "".join(out)


def cell_pixels():
    """Width and height of a character cell in pixels as the terminal reports them, or (0, 0)."""
    import fcntl
    import termios
    for fd in (2, 0, 1):
        try:
            rows, cols, xpx, ypx = struct.unpack("HHHH", fcntl.ioctl(fd, termios.TIOCGWINSZ, b"\0" * 8))
        except (OSError, struct.error):
            continue
        if rows and cols and xpx and ypx:
            return xpx // cols, ypx // rows
    return 0, 0


def graphics():
    """How the logo can be drawn here: ("sixel", cell width, cell height), ("rgb",) or ("256",).
    WALLSTREET_LOGO=blocks forces characters, =sixel forces pixels."""
    want = os.environ.get("WALLSTREET_LOGO", "")
    rgb = os.environ.get("COLORTERM", "") in ("truecolor", "24bit")
    pane = os.environ.get("TMUX_PANE")
    if os.environ.get("TMUX") and pane:
        # inside tmux the clients decide: every terminal looking at this pane must be able to
        try:
            session = subprocess.run(["tmux", "display-message", "-p", "-t", pane, "#{session_id}"],
                                     capture_output=True, text=True, timeout=3).stdout.strip()
            clients = [l.split("|") for l in subprocess.run(
                ["tmux", "list-clients", "-t", session, "-F",
                 "#{client_termfeatures}|#{client_cell_width}|#{client_cell_height}"],
                capture_output=True, text=True, timeout=3).stdout.splitlines() if l.count("|") == 2]
        except (OSError, subprocess.SubprocessError):
            clients = []
        feats = [set(c[0].split(",")) for c in clients]
        rgb = bool(feats) and all("RGB" in f for f in feats)
        cells = [(int(c[1] or 0), int(c[2] or 0)) for c in clients if c[1].isdigit() and c[2].isdigit()]
        if want != "blocks" and feats and all("sixel" in f for f in feats) \
                and len(cells) == len(clients) and all(w > 0 and h > 0 for w, h in cells):
            return ("sixel", min(w for w, _ in cells), min(h for _, h in cells))
        if want == "sixel":
            return ("sixel", 10, 20)      # asked for: a guess at the cell, when no client reports one
    elif want != "blocks" and (want == "sixel" or os.environ.get("TERM_PROGRAM") in ("iTerm.app", "WezTerm")):
        width, height = cell_pixels()
        if width and height:
            return ("sixel", width, height)
    return ("rgb",) if rgb else ("256",)


def logo_screen(symbol, cols, lines, mode):
    """What to write to show the logo: a picture where the terminal draws pixels,
    half blocks elsewhere."""
    if mode[0] != "sixel":
        lines_ = logo_lines(symbol, cols, lines, rgb=mode[0] == "rgb")
        return "\033[H" + "".join(l + "\033[K\n" for l in lines_[:-1]) + lines_[-1] + "\033[K\033[J"
    cell_w, cell_h = mode[1], mode[2]
    # a square of whole cells, never larger than a logo is delivered
    side = min((cols - 2) * cell_w, (lines - 2) * cell_h, 512 + 64)
    side = max(cell_h, side // cell_h * cell_h)
    used_cols, used_rows = -(-side // cell_w), side // cell_h
    top = max(0, (lines - 2 - used_rows) // 2)
    left = max(0, (cols - used_cols) // 2)
    picture = sixel(logo_grid(symbol, side))
    return ("\033[H\033[J\033[%d;%dH" % (top + 1, left + 1) + picture
            + "\033[%d;1H" % min(lines, top + used_rows + 2) + logo_caption(symbol, cols))


def cmd_logo():
    """The logo of the selected stock; follows the selection file."""
    seen, mode, tick = None, ("256",), 0
    sys.stdout.write("\033[?25l")
    try:
        while True:
            if tick % 10 == 0:
                mode = graphics()         # a terminal may attach later, or another one
            tick += 1
            now = (read_selection()[0], tuple(term_size()), mode)
            if now != seen:
                seen = now
                if now[0]:
                    sys.stdout.write(logo_screen(now[0], now[1][0], now[1][1], mode))
                    sys.stdout.flush()
                else:
                    draw(["", "\033[90m%s\033[0m" % "Select a stock."])
            time.sleep(0.3)
    finally:
        sys.stdout.write("\033[?25h")
    return 0


# ---------------------------------------------------------------- terminal

class Terminal:
    """Keys and mouse clicks from the pane, without waiting for Enter.

    cbreak keeps Ctrl-C a signal, so the widget's trap still ends the show.
    Mouse reporting needs "mouse on" in tmux; without it the keys still work.
    """
    def __init__(self):
        self.fd = sys.stdin.fileno()
        self.saved = None
        self.buffer = ""

    def __enter__(self):
        if os.isatty(self.fd):
            self.saved = termios.tcgetattr(self.fd)
            tty.setcbreak(self.fd)
            sys.stdout.write("\033[?1000h\033[?1006h\033[?25l")
            sys.stdout.flush()
        return self

    def __exit__(self, *exc):
        if self.saved is not None:
            sys.stdout.write("\033[?1000l\033[?1006l\033[?25h")
            sys.stdout.flush()
            termios.tcsetattr(self.fd, termios.TCSADRAIN, self.saved)
        return False

    def events(self, timeout):
        """Wait up to TIMEOUT seconds; return what was pressed or clicked."""
        if self.saved is None:
            time.sleep(timeout)
            return []
        ready, _, _ = select.select([self.fd], [], [], timeout)
        if ready:
            self.buffer += os.read(self.fd, 256).decode("utf-8", "replace")
        # an ESC that is still alone after a moment is the key, not a sequence
        final = self.buffer == "\x1b" and not select.select([self.fd], [], [], 0.05)[0]
        events, self.buffer = parse_input(self.buffer, final)
        return events


def parse_input(buffer, final=False):
    """Split raw terminal input into events; an unfinished sequence stays in the rest.

    Events: ("key", name) for up/down/left/right/enter/escape/backspace/delete or a
            single character, ("click", x, y) with 1-based cell coordinates,
            ("wheel", -1 | +1).
    FINAL says that nothing more is coming for now: a lone ESC is then the Escape key
    and not the start of a sequence.
    """
    events = []
    while buffer:
        m = re.match(r"\x1b\[<(\d+);(\d+);(\d+)([Mm])", buffer)
        if m:
            button, x, y, kind = int(m.group(1)), int(m.group(2)), int(m.group(3)), m.group(4)
            if button in (64, 65):
                events.append(("wheel", -1 if button == 64 else 1))
            elif kind == "M" and button & 3 == 0 and button < 32:
                events.append(("click", x, y))
            buffer = buffer[m.end():]
            continue
        m = re.match(r"\x1b(?:\[|O)([A-D])", buffer)
        if m:
            events.append(("key", {"A": "up", "B": "down", "C": "right", "D": "left"}[m.group(1)]))
            buffer = buffer[m.end():]
            continue
        if buffer.startswith("\x1b[3~"):
            events.append(("key", "delete"))
            buffer = buffer[4:]
            continue
        if buffer[0] == "\x1b":
            if re.fullmatch(r"\x1b(\[<?[\d;]*)?", buffer):
                if final and buffer == "\x1b":
                    events.append(("key", "escape"))
                    buffer = ""
                break                      # the rest of the sequence has not arrived yet
            m = re.match(r"\x1b\[[\d;?<]*[A-Za-z~]", buffer)
            if m:
                buffer = buffer[m.end():]  # a sequence this program has no use for
                continue
            events.append(("key", "escape"))
            buffer = buffer[1:]
            continue
        events.append(("key", "enter" if buffer[0] in "\r\n" else
                       "backspace" if buffer[0] in "\x7f\x08" else buffer[0]))
        buffer = buffer[1:]
    return events, buffer


def draw(lines):
    """Replace the pane's content without the flicker of a clear."""
    sys.stdout.write("\033[H" + "".join(line + "\033[K\n" for line in lines[:-1])
                     + (lines[-1] + "\033[K" if lines else "") + "\033[J")
    sys.stdout.flush()


# ------------------------------------------------------------------- browse

SECTIONS = (("MOST ACTIVE", "MostActiveByDollarVolume"), ("NASDAQ-100 MOVERS", "Nasdaq100Movers"),
            ("ADVANCERS", "MostAdvanced"), ("DECLINERS", "MostDeclined"))
SYMBOL = re.compile(r"[A-Za-z0-9.^-]{1,12}")
WATCH_MAX = 12


# ---------------------------------------------------------------- watchlist
#
# Stocks found with the search are kept in a list of their own, above the day's
# movers, until they are removed again.

def watchlist_path():
    return os.path.join(CACHE, "watchlist-demo.json" if DEMO else "watchlist.json")


def read_watchlist():
    """[(symbol, name)], newest first; a damaged file is an empty list."""
    try:
        with open(watchlist_path(), encoding="utf-8") as f:
            data = json.load(f)
        out = []
        for item in data:
            symbol = clean(item.get("symbol", ""))
            if SYMBOL.fullmatch(symbol) and symbol not in [s for s, _ in out]:
                out.append((symbol, clean(item.get("name", ""))[:80]))
        return out[:WATCH_MAX]
    except (OSError, ValueError, AttributeError, TypeError):
        return []


def write_watchlist(items):
    fd, tmp = tempfile.mkstemp(dir=CACHE, prefix=".tmp-")
    with os.fdopen(fd, "w", encoding="utf-8") as f:
        json.dump([{"symbol": s, "name": n} for s, n in items[:WATCH_MAX]], f)
    os.replace(tmp, watchlist_path())


def watch(symbol, name):
    """Put a stock at the top of the watchlist."""
    if SYMBOL.fullmatch(symbol or ""):
        write_watchlist([(symbol, name)] + [i for i in read_watchlist() if i[0] != symbol])


def unwatch(symbol):
    write_watchlist([i for i in read_watchlist() if i[0] != symbol])


def watch_rows():
    """The watchlist as table rows, with the quote of each stock."""
    out = []
    for symbol, name in read_watchlist():
        row = {"symbol": symbol, "name": name, "lastSalePrice": "", "lastSaleChange": "", "change": ""}
        if DEMO:
            found = next((r for key in ("MostActiveByDollarVolume", "Nasdaq100Movers")
                          for r in rows(key) if r.get("symbol") == symbol), None)
            if found:
                row = dict(found)
        else:
            q = quote(symbol)
            row["label"] = label(symbol)
            if q:
                row.update(lastSalePrice=price(q["last"]) + (" \u20ac" if q.get("currency") == "EUR" else ""),
                           lastSaleChange="%+.2f" % q["change"],
                           change="%+.2f%%" % q["pct"],
                           deltaIndicator="down" if q["change"] < 0 else "up")
        out.append(row)
    return out


# ------------------------------------------------------------------- search

def search(query):
    """Stocks and funds traded on an exchange whose symbol or name matches QUERY:
    [{"symbol", "name", "exchange"}], best match first, at most ten."""
    query = re.sub(r"\s+", " ", clean(query)).strip()[:40]
    if not query:
        return []
    if DEMO:
        q = query.lower()
        hits = [(sym, name) for sym, name, _ in DEMO_STOCKS if q in sym.lower() or q in name.lower()]
        hits.sort(key=lambda h: (not h[0].lower().startswith(q), h[0]))
        return [{"symbol": sym, "name": name, "exchange": "DEMO"} for sym, name in hits[:10]]
    url = "https://api.nasdaq.com/api/autocomplete/slookup/25?search=" + urllib.parse.quote(query, safe="")
    key = "search-%s.json" % re.sub(r"[^a-z0-9]", "_", query.lower())[:40]
    try:
        data = json.loads(cached(key, 3600, lambda: fetch(url)))["data"] or []
    except (ValueError, KeyError, TypeError):
        data = []
    out = []
    for item in data:
        try:
            symbol = clean(item.get("symbol") or "")
            # notes and mutual funds have no course to draw
            if item.get("asset") not in ("STOCKS", "ETF") or not SYMBOL.fullmatch(symbol):
                continue
            out.append({"symbol": symbol, "name": clean(item.get("name") or symbol),
                        "exchange": clean(item.get("exchange") or "")[:12]})
        except AttributeError:
            continue
    # what is not listed in the US - and the euro price of what is - from Lang & Schwarz;
    # both get their share of the ten lines
    # that search wants the name as the exchange writes it ("mercedes-benz"); a name typed
    # with spaces is tried with hyphens and then by its first word
    out = index_search(query) + out
    elsewhere = []
    for variant in dict.fromkeys((query, query.replace(" ", "-"), query.split(" ")[0])):
        elsewhere = ls_search(variant)
        if elsewhere:
            break
    room = max(10 - len(elsewhere), 5)
    return (out[:room] + elsewhere)[:10]


def search_lines(query, results, index, cols, lines, waiting=False):
    """The search view as LINES strings; result I is on line 3 + I (1-based)."""
    width = max(20, cols - 1)
    out = ["\033[1;33mSEARCH\033[0m", "\033[90m%s\033[0m" % ("-" * width)]
    room = max(0, lines - 4)
    name_w = max(8, width - 21)
    for i, r in enumerate(results[:room]):
        text = "\033[1;34m%-6s\033[39;22m %-*s \033[90m%12s\033[39m" % (
            (r.get("label") or r["symbol"])[:6], name_w, r["name"][:name_w], r["exchange"][:12])
        out.append("\033[48;5;238m%s\033[K\033[0m" % text if i == index else text + "\033[0m")
    if not results:
        note = ("Type a name or a symbol." if not query else
                "searching ..." if waiting else "Nothing found for \"%s\"." % query)
        out.append("\033[90m%s\033[0m" % note[:width])
    out += [""] * max(0, lines - 2 - len(out))
    out.append("\033[1;33msearch:\033[0m %s\033[7m \033[27m" % query[:max(0, width - 10)])
    out.append("\033[90m%s\033[0m" % "enter add to watchlist · ↑↓ choose · esc back"[:width])
    return out[:lines]


# -------------------------------------------------------------------- table

def table_rows(cols, lines):
    """The quote table as [(text, symbol or None, section)], cut to LINES like cmd_table."""
    out = []
    name_w = max(8, cols - 42)
    sections = [("INDICES", "index", index_rows()), ("WATCHLIST", "watch", watch_rows())]
    sections += [("INDEX MOVERS" if DEMO and key == "Nasdaq100Movers" else title, key, rows(key))
                 for title, key in SECTIONS]
    for title, key, data in sections:
        if not data:
            continue
        out.append(("\033[1;33m%s\033[0m" % title, None, key))
        out.append(("\033[90m%s\033[0m" % ("-" * (cols - 1)), None, key))
        for r in data:
            pct = percent(r)
            shown = "%+.2f%%" % pct if pct is not None else r.get("change", "")
            down = r.get("deltaIndicator") == "down" or shown.startswith("-")
            text = "\033[1;34m%-6s\033[39;22m %-*s \033[1;35m%10s\033[39;22m \033[1;%sm%10s %9s\033[39;22m" % (
                (r.get("label") or r.get("symbol", ""))[:6], name_w, r.get("name", "")[:name_w],
                r.get("lastSalePrice", "").lstrip("$")[:10],
                "31" if down else "32", r.get("lastSaleChange", "")[:10], shown[:9])
            out.append((text, r.get("symbol", ""), key))
        out.append(("", None, key))
    out = out[:max(3, lines)]
    while len(out) > 3 and out[-1][1] is None:
        out.pop()                           # no bare heading at the cut
    return out


def table_view(table, index, cols, lines):
    """The table pane: the rows with the selected one marked, and the hint line."""
    on_watchlist = bool(table) and index < len(table) and table[index][2] == "watch"
    hint = "click or ↑↓ select · / search · 1-5 span" + (" · d remove" if on_watchlist else "")
    view = [("\033[48;5;238m%s\033[K\033[0m" % text if i == index else text + "\033[0m")
            for i, (text, _, _) in enumerate(table)]
    view = view[:max(0, lines - 1)]              # the hint keeps its line, whatever the table
    view += [""] * max(0, lines - 1 - len(view))
    view.append("\033[90m%s\033[0m" % hint[:max(0, cols - 1)])
    return view


def cmd_browse():
    """The quote table with a selection - arrow keys, j/k, mouse wheel or a click -
    and a search: "/" or a click on the hint line."""
    with Terminal() as term:
        table, shown, size, loaded, index = [], None, None, 0.0, 0
        query, results, at_result, searched = None, [], 0, None      # query is None: not searching
        while True:
            now_size = tuple(term_size())
            if now_size != size or time.time() - loaded >= 60:
                size, loaded = now_size, time.time()
                table = table_rows(size[0], size[1] - 2)
                picks = [i for i, row in enumerate(table) if row[1]]
                wanted = read_selection()[0]
                index = next((i for i in picks if table[i][1] == wanted), picks[0] if picks else 0)
                shown = None
            picks = [i for i, row in enumerate(table) if row[1]]
            if query is not None:
                state = ("search", query, at_result, searched)
                if shown != state:
                    draw(search_lines(query, results, at_result, size[0], size[1], waiting=searched != query))
                    shown = state
            elif picks and shown != index:
                if table[index][1] != read_selection()[0]:
                    write_selection(symbol=table[index][1])
                draw(table_view(table, index, size[0], size[1]))
                shown = index
            elif not picks and shown != "empty":
                draw(["\033[33mNo market data available right now.\033[0m", "",
                      "\033[90m/ search\033[0m"])
                shown = "empty"
            events = term.events(0.5 if query is None else 0.25)
            if query is not None and not events and searched != query:
                results, searched, at_result = search(query), query, 0   # typing has paused: look it up
                continue
            for event in events:
                if query is not None:
                    chosen = None
                    if event == ("key", "escape"):
                        query, shown = None, None
                    elif event == ("key", "enter"):
                        if searched != query:
                            results, searched, at_result = search(query), query, 0
                        chosen = results[at_result] if results else None
                    elif event[0] == "click" and 0 <= event[2] - 3 < len(results):
                        chosen = results[event[2] - 3]
                    elif event[0] == "wheel" or event in (("key", "up"), ("key", "down")):
                        step = event[1] if event[0] == "wheel" else (-1 if event[1] == "up" else 1)
                        at_result = max(0, min(len(results) - 1, at_result + step))
                    elif event == ("key", "backspace"):
                        query = query[:-1]
                    elif event[0] == "key" and len(event[1]) == 1 and event[1].isprintable() and len(query) < 40:
                        query += event[1]
                    if chosen:
                        watch(chosen["symbol"], chosen["name"])
                        write_selection(symbol=chosen["symbol"])
                        query, shown, loaded = None, None, 0.0          # back to the table, reloaded
                    continue
                if event == ("key", "/") or event == ("key", "s") or \
                        (event[0] == "click" and event[2] == size[1]):
                    query, results, at_result, searched, shown = "", [], 0, "", None
                    continue
                if not picks:
                    continue
                at = picks.index(index) if index in picks else 0
                if event[0] == "click":
                    line = event[2] - 1
                    if line in picks:
                        index = line
                elif event[0] == "wheel" or event in (("key", "up"), ("key", "down"),
                                                       ("key", "k"), ("key", "j")):
                    step = event[1] if event[0] == "wheel" else (-1 if event[1] in ("up", "k") else 1)
                    index = picks[max(0, min(len(picks) - 1, at + step))]
                elif event[0] == "key" and event[1] in "12345":
                    write_selection(span=SPAN_KEYS[int(event[1]) - 1])
                elif event[0] == "key" and event[1] in ("d", "delete", "backspace") \
                        and table[index][2] == "watch":
                    unwatch(table[index][1])
                    loaded, shown = 0.0, None                            # reload without it
    return 0


def cmd_chart():
    """The chart of the selected stock; follows the selection file."""
    with Terminal() as term:
        seen, size, data, loaded = None, None, None, 0.0
        while True:
            selection, now_size = read_selection(), tuple(term_size())
            stale = time.time() - loaded >= 60
            if selection != seen and selection[0]:
                # say so at once: the first request for a symbol takes a moment
                draw(["\033[1;34m%s\033[0m" % selection[0], "\033[90mloading ...\033[0m"])
            if selection != seen or stale:
                data = history(selection[0], selection[1]) if selection[0] else None
                loaded = time.time()
            if selection != seen or now_size != size or stale:
                seen, size = selection, now_size
                draw(chart_lines(data, selection[1], size[0], size[1]) or [""])
            for event in term.events(0.25):
                keys = SPAN_KEYS
                if event[0] == "key" and event[1] in "12345":
                    write_selection(span=keys[int(event[1]) - 1])
                elif event[0] == "click" and tab_at(event[1], event[2]):
                    write_selection(span=tab_at(event[1], event[2]))      # a click on a tab opens it
                elif event[0] == "click" or event in (("key", "right"), ("key", "enter"), ("key", " ")):
                    write_selection(span=keys[(keys.index(selection[1]) + 1) % len(keys)])
                elif event == ("key", "left"):
                    write_selection(span=keys[(keys.index(selection[1]) - 1) % len(keys)])
    return 0


def cmd_demofeed():
    """A local RSS file of the invented headlines, for the feed reader."""
    from xml.sax.saxutils import escape
    now = time.time()
    items = "".join(
        "<item><title>%s</title><link>https://example.com/%d</link>"
        "<guid>demo-%d</guid><pubDate>%s</pubDate>"
        "<description>%s.</description></item>" % (
            escape(t), i, i,
            time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime(now - i * 1740)),
            escape(t))
        for i, t in enumerate(DEMO_HEADLINES))
    feed = os.path.join(CACHE, "demo-feed.xml")
    with open(feed, "w", encoding="utf-8") as f:
        f.write('<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel>'
                "<title>Wall Street Wire (demo)</title><link>https://example.com/</link>"
                "<description>Invented headlines</description>%s</channel></rss>" % items)
    urls = os.path.join(CACHE, "demo.urls")
    with open(urls, "w", encoding="utf-8") as f:
        f.write("file://%s\n" % feed)
    print(urls)
    return 0


def cmd_image():
    if DEMO:
        print(os.path.join(HERE, "demo.jpg"))
        return 0
    pics = sorted({p for _, p in feeds() if p})
    random.shuffle(pics)
    for url in pics[:5]:
        name = "img-%08x.jpg" % (zlib.crc32(url.encode()) & 0xffffffff)
        data = cached(name, 86400, lambda: fetch(url))
        if data:
            print(os.path.join(CACHE, name))
            return 0
    return 1


def cmd_marquee(color, delay, text):
    text = re.sub(r"\s+", " ", clean(text)).strip()
    if not text:
        return 1
    code = COLORS.get(color, 37)
    delay = float(delay)
    cols = max(10, term_size().columns - 1)
    band = " " * cols + text + " " * cols
    try:
        sys.stdout.write("\033[?25l")
        for i in range(len(band) - cols + 1):
            cols_now = max(10, term_size().columns - 1)
            sys.stdout.write("\r\033[1;%dm%s\033[0m\033[K" % (
                code, band[i:i + cols][:cols_now]))
            sys.stdout.flush()
            time.sleep(delay)
    finally:
        sys.stdout.write("\033[?25h\r")
    return 0


def main(argv):
    cmd = argv[1] if len(argv) > 1 else ""
    if cmd == "table":
        return cmd_table()
    if cmd == "movers" and len(argv) > 2:
        return cmd_movers(argv[2])
    if cmd == "headlines":
        return cmd_headlines()
    if cmd == "image":
        return cmd_image()
    if cmd == "browse":
        return cmd_browse()
    if cmd == "chart":
        return cmd_chart()
    if cmd == "logo":
        return cmd_logo()
    if cmd == "demofeed":
        return cmd_demofeed()
    if cmd == "cachedir":
        print(CACHE)
        return 0
    if cmd == "marquee" and len(argv) > 4:
        return cmd_marquee(argv[2], argv[3], argv[4])
    sys.stderr.write(__doc__ or "usage: wsdata table|movers|headlines|image|marquee\n")
    return 2


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv))
    except (KeyboardInterrupt, BrokenPipeError):
        sys.exit(130)
