"""Check Salary Box tickets on your own machine. Standard library only, and nothing is sent anywhere.

    python check_tickets.py VERIFY_KEY < tickets.csv > results.csv

Each input line is "application-id,ticket". Each output line is "application-id,result", where the result is
below (the minimum is at or below your ceiling), above, or invalid (not a ticket for this listing).

A position that has had more than one listing has more than one verify key. Give all of them:

    python check_tickets.py KEY_1 KEY_2 < tickets.csv > results.csv

A ticket reads as below or above under the key of the listing it was made for and as invalid under every other
key, so each output line becomes "application-id,result,n", where n says which key gave the result.
"""
import base64
import binascii
import hashlib
import hmac
import sys


def unb64(s: str) -> bytes:
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))


def check(verify_key: str, ticket: str) -> str:
    try:
        key, raw = unb64(verify_key), unb64(ticket)
    except (binascii.Error, ValueError):
        return "invalid"
    if len(key) != 32 or len(raw) != 32:
        return "invalid"
    nonce, tag = raw[:16], raw[16:]
    # The ticket is a nonce and a tag. The tag was made with your key over the nonce and the answer, so
    # the answer is whichever of the two possibilities reproduces the tag.
    for bit, result in ((1, "below"), (0, "above")):
        expected = hmac.new(key, nonce + bytes([bit]), hashlib.sha256).digest()[:16]
        if hmac.compare_digest(tag, expected):
            return result
    return "invalid"


def check_any(verify_keys: list[str], ticket: str) -> str:
    for n, verify_key in enumerate(verify_keys, start=1):
        result = check(verify_key, ticket)
        if result != "invalid":
            return result if len(verify_keys) == 1 else f"{result},{n}"
    return "invalid"


if __name__ == "__main__":
    for line in sys.stdin:
        application_id, _, ticket = line.strip().partition(",")
        if ticket:
            print(f"{application_id},{check_any(sys.argv[1:], ticket.strip())}")
