#!/usr/bin/env python3
"""Keep a local JSON copy of FindOpera's operas up to date.

FindOpera's GraphQL API publishes every edit to the catalog as a change log,
`recordChanges`, read oldest first. This script reads the log for the operas
table and applies each entry to a local JSON file. Each entry is one version
of one opera, with the row that version wrote:

  * a version that left the opera in place -> store its title and English title
  * a version that removed it              -> drop it

Applied in order, the last version of each opera wins. A merge counts as a
removal. It copies nothing onto the opera that survives, and that opera has
entries of its own in the log.

The file also keeps the cursor of the last entry applied, so each run resumes
where the last one stopped. The first run reads the whole log. Standard
library only, and reading needs no account.

    python3 sync_operas.py [cache-file]     # default: operas_cache.json
"""

import json
import os
import sys
import time
import urllib.error
import urllib.request

API = "https://findopera.com/api/graphql"
PAGE_SIZE = 500  # the most the API returns at once

QUERY = """
query ($after: String, $first: Int!) {
  recordChanges(table: OPERAS, order: ASC, after: $after, first: $first) {
    pageInfo { hasNextPage endCursor }
    edges {
      node {
        recordId
        deletion { mergedIntoId }
        row { ... on OperaRow { id title englishTitle } }
      }
    }
  }
}
"""


def graphql(query, variables):
    body = json.dumps({"query": query, "variables": variables}).encode()
    request = urllib.request.Request(
        API, data=body, headers={"Content-Type": "application/json"}
    )
    for attempt in range(5):
        try:
            with urllib.request.urlopen(request) as response:
                payload = json.load(response)
            break
        except urllib.error.HTTPError as error:
            # 429 means rate limited, and Retry-After says for how long.
            # 503 means briefly down, as during a deploy.
            if error.code not in (429, 503) or attempt == 4:
                raise
            time.sleep(int(error.headers.get("Retry-After", 10)))
    if "errors" in payload:
        raise RuntimeError(payload["errors"])
    return payload["data"]


def apply(operas, node):
    if node["deletion"]:
        operas.pop(node["recordId"], None)
    else:
        # The opera as this version wrote it. A later entry for the same opera
        # replaces it.
        opera = node["row"]
        # `id` comes back as a number and `recordId` as a string. Key on the
        # string, or a later removal of this opera would not find it.
        operas[str(opera["id"])] = {
            "title": opera["title"],
            "englishTitle": opera["englishTitle"],
        }


def save(path, cache):
    # Write a new file and swap it in, so a crash leaves the old one intact.
    with open(path + ".tmp", "w") as f:
        json.dump(cache, f, ensure_ascii=False, indent=1)
    os.replace(path + ".tmp", path)


def sync(path):
    try:
        with open(path) as f:
            cache = json.load(f)
    except FileNotFoundError:
        cache = {"cursor": None, "operas": {}}

    applied = 0
    while True:
        variables = {"after": cache["cursor"], "first": PAGE_SIZE}
        page = graphql(QUERY, variables)["recordChanges"]
        for edge in page["edges"]:
            apply(cache["operas"], edge["node"])
        applied += len(page["edges"])

        # Save after every page, so a crash repeats at most one page, which is
        # harmless. An empty page has no endCursor: keep the one we have, or
        # the next run starts over from the beginning.
        if page["pageInfo"]["endCursor"]:
            cache["cursor"] = page["pageInfo"]["endCursor"]
            save(path, cache)
        if not page["pageInfo"]["hasNextPage"]:
            break

    print(f"{applied} changes applied, {len(cache['operas'])} operas")


if __name__ == "__main__":
    sync(sys.argv[1] if len(sys.argv) > 1 else "operas_cache.json")
