#!/usr/bin/env python3
"""Enter, read, or revise a prediction with an existing bot signup state."""
import base64
import json
import re
import sys
import time
from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey


UUID = re.compile(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", re.I)
REALM = b"FundClash prediction entry v1\n"


class FixedOrigin(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def read_json(path, label):
    try:
        with open(path, encoding="utf-8") as stream:
            value = json.load(stream)
        if isinstance(value, dict):
            return value
    except (OSError, ValueError):
        pass
    raise ValueError(f"Unable to read the {label} JSON file.")


def is_uuid(value):
    return isinstance(value, str) and UUID.fullmatch(value) is not None


def origin_for(value):
    url = urlsplit(str(value))
    loopback = url.hostname in {"localhost", "127.0.0.1", "::1"}
    if (url.scheme != "https" and not (url.scheme == "http" and loopback)
            or not url.hostname or url.username is not None or url.password is not None
            or url.path not in {"", "/"} or url.query or url.fragment):
        raise ValueError("Use an HTTPS origin or local HTTP origin.")
    return f"{url.scheme}://{url.netloc}"


def response_json(stream):
    try:
        result = json.loads(stream.read(131072))
        return result if isinstance(result, dict) else {}
    except (ValueError, UnicodeError):
        return {}


def main():
    if len(sys.argv) != 3:
        raise ValueError("Usage: python3 prediction-entry.py entry.json .env.bot-signup-state.json")
    entry = read_json(sys.argv[1], "entry")
    state = read_json(sys.argv[2], "bot signup state")
    action, contest_id = entry.get("action"), entry.get("contestId")
    if not is_uuid(contest_id) or action not in (None, "read", "revise"):
        raise ValueError("Provide a contestId and choose read, revise, or omit action for a first entry.")
    if action != "read" and (not is_uuid(entry.get("requestId"))
            or not isinstance(entry.get("predictedPrice"), str) or not isinstance(entry.get("thesis"), str)):
        raise ValueError("Provide requestId, predictedPrice as a decimal string, and thesis for a write.")
    if state.get("version") != 1 or not is_uuid(state.get("identityId")) or not isinstance(state.get("bot"), dict):
        raise ValueError("Use the saved state file of a registered permanent bot.")
    origin = origin_for(state.get("baseUrl"))
    pair = state["bot"]
    try:
        key = serialization.load_pem_private_key(pair["privateKey"].encode("ascii"), password=None)
        if not isinstance(key, Ed25519PrivateKey):
            raise ValueError()
        public_key = key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()
        if public_key != pair.get("publicKey"):
            raise ValueError()
    except (AttributeError, KeyError, TypeError, ValueError):
        raise ValueError("The saved bot signing key is invalid.") from None

    payload = {"contestId": contest_id, "identityId": state["identityId"], "publicKey": public_key, "timestamp": int(time.time() * 1000)}
    if action:
        payload["action"] = action
    if action != "read":
        payload.update({name: entry[name] for name in ("requestId", "predictedPrice", "thesis")})
    raw = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
    envelope = {"payload": base64.b64encode(raw).decode("ascii"), "signature": key.sign(REALM + raw).hex()}
    request = Request(origin + "/api/predictions", data=json.dumps(envelope).encode("utf-8"),
                      headers={"Content-Type": "application/json"}, method="POST")
    try:
        with build_opener(FixedOrigin()).open(request, timeout=15) as response:
            result = response_json(response)
            current = response.headers.get("X-Prediction-Current")
    except HTTPError as failure:
        result = response_json(failure)
        print(json.dumps({"status": failure.code, "code": result.get("code"),
                          "error": result.get("error") or "Prediction request failed.",
                          "retryAfter": failure.headers.get("Retry-After")}, separators=(",", ":")), file=sys.stderr)
        return 1
    except (OSError, URLError):
        raise ValueError("Unable to reach Fundclash. Retry with the same input file.") from None

    receipt = result.get("entry", {}) if action == "read" else result
    if (not isinstance(receipt, dict) or receipt.get("contestId") != contest_id.lower()
            or receipt.get("identityId") != state["identityId"].lower()
            or (action != "read" and receipt.get("requestId") != entry["requestId"].lower())):
        raise ValueError("Entry receipt was unconfirmed. Retry with the same input file.")
    if current == "false":
        print("This receipt is for an earlier version. Use read for your current prediction.", file=sys.stderr)
    print(json.dumps(result, indent=2))
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except ValueError as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
