#!/usr/bin/env python3
"""Build, or bring up to date, a SQLite copy of the whole FindOpera catalog.

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

  * a version that left the record in place -> store its row
  * a version that removed it               -> delete it

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

The file also keeps the cursor of the last entry applied, in the same
transaction as the entries, so each run resumes exactly where the last one
stopped.

When the catalog gains a table, a copy of this script older than the table
skips its entries and says so, rather than stopping. The file remembers which
tables it has kept, and a newer copy, which knows the table, reads that table's
entries from the start of the log before carrying on. So an old copy keeps the
rest of the catalog current, and the new table arrives whenever the script is
updated. The first run reads the whole log, which takes a while. To skip it,
start from the snapshot FindOpera publishes every week, which is this script's
own output (see https://findopera.com/data):

    curl -LO https://findopera.com/findopera.db.zip
    unzip findopera.db.zip
    python3 sync_catalog.py findopera.db      # fetches only what changed since

Standard library only, and reading needs no account. A token from
https://findopera.com/auth, in FINDOPERA_TOKEN, raises the rate limit from 60
requests a minute to 600, which makes the first full run much quicker.

    python3 sync_catalog.py [db-file]         # default: findopera.db
"""

import argparse
import datetime
import json
import os
import sqlite3
import sys
import time
import urllib.error
import urllib.request

API = os.environ.get("FINDOPERA_API", "https://findopera.com/api/graphql")
PAGE_SIZE = 500  # the most the API returns at once

# Bumped whenever the tables below change shape. A file written by another
# version is refused rather than patched, since a column this version adds
# would be empty for every record the file already holds.
FORMAT = 1

# Every table the change log reports, and where each column comes from.
#
# `type` names the row type, `OperaRow` for `Opera`, and a column is (name,
# SQLite type, field on that row). A reference is the id it holds, as
# `composerId`. The names match the catalog's own tables. `merged_into_id` is
# left out, because it is null on every record still in the catalog, and those
# are the only ones this file keeps.
TABLES = {
    "recordings": {
        "type": "Recording",
        "key": ["id"],
        "columns": [
            ("id", "INTEGER", "id"),
            ("year", "INTEGER", "year"),
            ("month", "INTEGER", "month"),
            ("day", "INTEGER", "day"),
            ("opera_id", "INTEGER", "operaId"),
            ("conductor_id", "INTEGER", "conductorId"),
            ("orchestra", "TEXT", "orchestra"),
            ("chorus", "TEXT", "chorus"),
            ("operaclass_id", "INTEGER", "operaclassId"),
        ],
    },
    "portrayals": {
        "type": "Portrayal",
        "key": ["id"],
        "columns": [
            ("id", "INTEGER", "id"),
            ("recording_id", "INTEGER", "recordingId"),
            ("singer_id", "INTEGER", "singerId"),
            ("character_id", "INTEGER", "characterId"),
            ("noted", "INTEGER", "noted"),
        ],
    },
    "characters": {
        "type": "Character",
        "key": ["id"],
        "columns": [
            ("id", "INTEGER", "id"),
            ("name", "TEXT", "name"),
            ("english_name", "TEXT", "englishName"),
            ("opera_id", "INTEGER", "operaId"),
        ],
    },
    "operas": {
        "type": "Opera",
        "key": ["id"],
        "columns": [
            ("id", "INTEGER", "id"),
            ("title", "TEXT", "title"),
            ("english_title", "TEXT", "englishTitle"),
            ("composer_id", "INTEGER", "composerId"),
            ("librettist", "TEXT", "librettist"),
            ("wikipedia_url", "TEXT", "wikipediaUrl"),
            ("language_id", "INTEGER", "languageId"),
            ("operaclass_id", "INTEGER", "operaclassId"),
            ("imslp_url", "TEXT", "imslpUrl"),
        ],
    },
    "singers": {
        "type": "Singer",
        "key": ["id"],
        "columns": [
            ("id", "INTEGER", "id"),
            ("first_name", "TEXT", "firstName"),
            ("last_name", "TEXT", "lastName"),
            ("born", "INTEGER", "born"),
            ("died", "INTEGER", "died"),
            ("wikipedia_url", "TEXT", "wikipediaUrl"),
            ("operaclass_id", "INTEGER", "operaclassId"),
            ("spotify_artist_id", "TEXT", "spotifyArtistId"),
        ],
    },
    "conductors": {
        "type": "Conductor",
        "key": ["id"],
        "columns": [
            ("id", "INTEGER", "id"),
            ("first_name", "TEXT", "firstName"),
            ("last_name", "TEXT", "lastName"),
            ("born", "INTEGER", "born"),
            ("died", "INTEGER", "died"),
            ("wikipedia_url", "TEXT", "wikipediaUrl"),
            ("operaclass_id", "INTEGER", "operaclassId"),
            ("spotify_artist_id", "TEXT", "spotifyArtistId"),
        ],
    },
    "composers": {
        "type": "Composer",
        "key": ["id"],
        "columns": [
            ("id", "INTEGER", "id"),
            ("first_name", "TEXT", "firstName"),
            ("last_name", "TEXT", "lastName"),
            ("born", "INTEGER", "born"),
            ("died", "INTEGER", "died"),
            ("wikipedia_url", "TEXT", "wikipediaUrl"),
            ("operaclass_id", "INTEGER", "operaclassId"),
            ("spotify_artist_id", "TEXT", "spotifyArtistId"),
            ("imslp_url", "TEXT", "imslpUrl"),
        ],
    },
    "languages": {
        "type": "Language",
        "key": ["id"],
        "columns": [
            ("id", "INTEGER", "id"),
            ("name", "TEXT", "name"),
            ("wikipedia_category", "TEXT", "wikipediaCategory"),
            ("abbreviation", "TEXT", "abbreviation"),
        ],
    },
    "upcs": {
        "type": "Upc",
        "key": ["upc"],
        "columns": [
            ("upc", "TEXT", "upc"),
        ],
    },
    "recording_upcs": {
        "type": "RecordingUpc",
        "key": ["recording_id", "upc_id"],
        "columns": [
            ("recording_id", "INTEGER", "recordingId"),
            ("upc_id", "TEXT", "upcId"),
        ],
    },
    "spotify_albums": {
        "type": "SpotifyAlbum",
        "key": ["spotify_album_id"],
        "columns": [
            ("spotify_album_id", "TEXT", "id"),
            ("upc_id", "TEXT", "upcId"),
            ("album_name", "TEXT", "albumName"),
        ],
    },
    "apple_music_albums": {
        "type": "AppleMusicAlbum",
        "key": ["apple_music_album_id"],
        "columns": [
            ("apple_music_album_id", "TEXT", "id"),
            ("upc_id", "TEXT", "upcId"),
        ],
    },
    "tidal_albums": {
        "type": "TidalAlbum",
        "key": ["tidal_album_id"],
        "columns": [
            ("tidal_album_id", "TEXT", "id"),
            ("upc_id", "TEXT", "upcId"),
        ],
    },
    "presto_music_albums": {
        "type": "PrestoMusicAlbum",
        "key": ["presto_music_album_id"],
        "columns": [
            ("presto_music_album_id", "TEXT", "slug"),
            ("upc_id", "TEXT", "upcId"),
            ("is_streaming", "INTEGER", "isStreaming"),
        ],
    },
    "naxos_albums": {
        "type": "NaxosAlbum",
        "key": ["naxos_album_id"],
        "columns": [
            ("naxos_album_id", "TEXT", "catalogueId"),
            ("upc_id", "TEXT", "upcId"),
        ],
    },
    "music_brainz_release_groups": {
        "type": "MusicBrainzReleaseGroup",
        "key": ["music_brainz_release_group_id"],
        "columns": [
            ("music_brainz_release_group_id", "TEXT", "id"),
            ("recording_id", "INTEGER", "recordingId"),
        ],
    },
    "music_brainz_releases": {
        "type": "MusicBrainzRelease",
        "key": ["music_brainz_release_id"],
        "columns": [
            ("music_brainz_release_id", "TEXT", "id"),
            ("upc_id", "TEXT", "upcId"),
        ],
    },
    "discogs_releases": {
        "type": "DiscogsRelease",
        "key": ["discogs_release_id"],
        "columns": [
            ("discogs_release_id", "TEXT", "id"),
            ("master_id", "INTEGER", "masterId"),
            ("upc_id", "TEXT", "upcId"),
        ],
    },
    "recording_discogs_releases": {
        "type": "RecordingDiscogsRelease",
        "key": ["recording_id", "discogs_release_id"],
        "columns": [
            ("recording_id", "INTEGER", "recordingId"),
            ("discogs_release_id", "TEXT", "discogsReleaseId"),
        ],
    },
    "album_cover_art": {
        "type": "AlbumCoverArt",
        "key": ["upc"],
        "columns": [
            ("upc", "TEXT", "upc"),
            ("image_url", "TEXT", "imageUrl"),
            ("source", "TEXT", "source"),
        ],
    },
    "recording_urls": {
        "type": "RecordingURL",
        "key": ["id"],
        "columns": [
            ("id", "INTEGER", "id"),
            ("recording_id", "INTEGER", "recordingId"),
            ("url", "TEXT", "url"),
        ],
    },
    "wikipedia_images": {
        "type": "WikipediaImage",
        "key": ["wikipedia_url"],
        "columns": [
            ("wikipedia_url", "TEXT", "wikipediaUrl"),
            ("image_url", "TEXT", "imageUrl"),
        ],
    },
}


def alias(table, column):
    # Each field is renamed for its table. GraphQL refuses a query in which
    # two types return the same name with different types, and these do: `id`
    # is a number on `OperaRow` and a string on `SpotifyAlbumRow`.
    return f"{table}_{column}"


def build_query(table=None):
    fragments = "\n".join(
        f"        ... on {table['type']}Row {{ "
        + " ".join(f"{alias(name, column)}: {field}" for column, _, field in table["columns"])
        + " }"
        for name, table in TABLES.items()
    )
    # Without `table:` this is the whole log, and one cursor covers every
    # table. With it, one table's entries alone, which is how a table this
    # file has not been keeping is filled in. That cursor belongs to that
    # table's feed and is kept apart from the main one.
    narrowed = f", table: {table.upper()}" if table else ""
    return f"""
query ($after: String, $first: Int!) {{
  recordChanges(order: ASC, after: $after, first: $first{narrowed}) {{
    pageInfo {{ hasNextPage endCursor }}
    edges {{
      node {{
        tableName
        recordId
        deletion {{ mergedIntoId }}
        row {{
{fragments}
        }}
      }}
    }}
  }}
}}
"""


QUERY = build_query()


def graphql(query, variables):
    body = json.dumps({"query": query, "variables": variables}).encode()
    headers = {"Content-Type": "application/json"}
    token = os.environ.get("FINDOPERA_TOKEN")
    if token:
        headers["Authorization"] = f"Bearer {token}"
    request = urllib.request.Request(API, data=body, headers=headers)
    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 create_tables(db):
    for name, table in TABLES.items():
        columns = ", ".join(f"{column[0]} {column[1]}" for column in table["columns"])
        key = ", ".join(table["key"])
        db.execute(f"CREATE TABLE IF NOT EXISTS {name} ({columns}, PRIMARY KEY ({key}))")
    db.execute(
        "CREATE TABLE IF NOT EXISTS sync_state (key TEXT PRIMARY KEY, value TEXT)"
    )


def get_state(db, key):
    row = db.execute("SELECT value FROM sync_state WHERE key = ?", (key,)).fetchone()
    return row[0] if row else None


def set_state(db, key, value):
    db.execute(
        "INSERT OR REPLACE INTO sync_state (key, value) VALUES (?, ?)", (key, value)
    )


def kept_tables(db):
    """The tables this file has been kept current for, from the start of the log."""
    value = get_state(db, "tables")
    if value is None:
        # A file from before this was recorded. Those were written by a copy
        # that stopped at any table it did not know, so it holds every table
        # it knew, which is every table here: the first one added after it,
        # Discogs, had no entries until the copy that knows it was published.
        return set(TABLES)
    return set(json.loads(value))


def keep(db, tables):
    set_state(db, "tables", json.dumps(sorted(tables)))


def apply(db, node, skipped):
    name = node["tableName"]
    table = TABLES.get(name)
    if table is None:
        # Skipped rather than stopped at. A copy of this script that knows the
        # table will find it missing from the ones this file has kept, and
        # read its entries from the start of the log, so moving the cursor
        # past them loses nothing for good.
        skipped[name] = skipped.get(name, 0) + 1
        return

    # The row this version wrote. A later entry for the same record replaces
    # it, so an old value lasts only until the log reaches the newer one. A
    # deletion's row still holds the record's key, which is all a delete
    # needs.
    row = node["row"]

    if node["deletion"]:
        where = " AND ".join(f"{column} = ?" for column in table["key"])
        keys = [row[alias(name, column)] for column in table["key"]]
        db.execute(f"DELETE FROM {name} WHERE {where}", keys)
        return

    values = [row[alias(name, column)] for column, _, _ in table["columns"]]
    names = ", ".join(column[0] for column in table["columns"])
    marks = ", ".join("?" for _ in table["columns"])
    db.execute(f"INSERT OR REPLACE INTO {name} ({names}) VALUES ({marks})", values)


def sync(path):
    db = sqlite3.connect(path)
    create_tables(db)
    found = get_state(db, "format")
    if found is None:
        set_state(db, "format", str(FORMAT))
        db.commit()
    elif found != str(FORMAT):
        sys.exit(
            f"{path} was written in format {found}, and this script writes "
            f"format {FORMAT}. Download a fresh snapshot, or start a new file."
        )

    skipped = {}
    kept = kept_tables(db)
    if get_state(db, "cursor") is None:
        # A file starting from nothing reads every table from the start.
        kept = set(TABLES)
    with db:
        keep(db, kept)

    # Tables this script knows and this file has not been keeping, because an
    # older copy wrote it. Each is read from the start of the log on its own
    # feed, with its own cursor so an interrupted fill resumes. Filled to the
    # end of the log, which the main read below then repeats from its own
    # cursor: entries are applied in order, so the last one still wins.
    for name in sorted(set(TABLES) - kept):
        print(f"filling in {name}, which this file has not kept", file=sys.stderr)
        read(db, build_query(name), f"cursor:{name}", skipped)
        with db:
            kept.add(name)
            keep(db, kept)
            db.execute("DELETE FROM sync_state WHERE key = ?", (f"cursor:{name}",))

    read(db, QUERY, "cursor", skipped)

    for name, count in sorted(skipped.items()):
        print(
            f"skipped {count} changes to {name}, a table this script does not "
            "know. Download the current sync_catalog.py, which fills it in from "
            "the start of the log.",
            file=sys.stderr,
        )
    db.close()


def read(db, query, cursor_key, skipped):
    applied = 0
    while True:
        variables = {"after": get_state(db, cursor_key), "first": PAGE_SIZE}
        page = graphql(query, variables)["recordChanges"]

        # One transaction per page, cursor included, so a crash leaves the
        # file at the end of the last whole page and the next run picks up
        # from there. An empty page has no endCursor: keep the one we have,
        # or the next run starts over from the beginning.
        with db:
            for edge in page["edges"]:
                apply(db, edge["node"], skipped)
            if page["pageInfo"]["endCursor"]:
                set_state(db, cursor_key, page["pageInfo"]["endCursor"])
            now = datetime.datetime.now(datetime.timezone.utc)
            set_state(db, "synced_at", now.isoformat(timespec="seconds"))
        applied += len(page["edges"])
        print(f"{applied} changes applied", file=sys.stderr)

        if not page["pageInfo"]["hasNextPage"]:
            break


def describe():
    """What this script reads and writes, for FindOpera's own tests."""
    tables = {name: [column[0] for column in table["columns"]] for name, table in TABLES.items()}
    print(json.dumps({"query": QUERY, "tables": tables}))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("db", nargs="?", default="findopera.db")
    parser.add_argument("--describe", action="store_true", help=argparse.SUPPRESS)
    args = parser.parse_args()
    if args.describe:
        describe()
    else:
        sync(args.db)
