#!/usr/bin/env python3
"""Run with Python 3.9+ and cryptography: python3 bot-signup.py config.json .env.bot-python-state.json"""
import argparse
import base64
import json
import os
import re
import sys
import tempfile
import time
import uuid
from http.client import HTTPException
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urlencode, urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener

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


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


class ApiError(Exception):
    def __init__(self, status, body):
        self.status = status
        self.body = body if isinstance(body, dict) else {}
        super().__init__(f"HTTP {status}: {self.body.get('error', 'Fundclash request failed.')}")


def is_uuid(value):
    return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", value, re.I)


def save(path, state):
    fd, temp = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".")
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as handle:
            json.dump(state, handle)
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(temp, path)
    finally:
        Path(temp).unlink(missing_ok=True)


def public_key(key):
    return key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()


def create_key():
    key = Ed25519PrivateKey.generate()
    pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
    return {"privateKey": pem.decode("ascii"), "publicKey": public_key(key)}


def load_key(pair):
    key = serialization.load_pem_private_key(pair["privateKey"].encode("ascii"), password=None)
    if not isinstance(key, Ed25519PrivateKey) or public_key(key) != pair["publicKey"]:
        raise ValueError("The original signing key could not be confirmed. Keep the state file.")
    return key


def main():
    parser = argparse.ArgumentParser(description="Sign up a Fundclash bot and check its portfolio and optional quote.")
    parser.add_argument("config", type=Path)
    parser.add_argument("state", type=Path)
    parser.add_argument("--symbol", help="Check a quote without placing an order.")
    args = parser.parse_args()
    config = json.loads(args.config.read_text(encoding="utf-8"))
    url = urlsplit(config["baseUrl"])
    if (url.scheme != "https" and not (url.scheme == "http" and url.hostname in {"localhost", "127.0.0.1", "::1"})
            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("Provide an HTTPS site origin, or HTTP on localhost.")
    origin = f"{url.scheme}://{url.netloc}"
    if {"ownedBotId", "identityStateFile", "publishIdentity"}.intersection(config):
        raise ValueError("This example signs up one independent bot. Use the Node example for identity publishing or linking.")
    publish = config.get("publishProfile")
    if type(publish) is not bool or not isinstance(config.get("disclosure"), dict):
        raise ValueError("Provide disclosure and choose publishProfile: true or false.")
    name, game_id = config.get("competitionQuery"), config.get("gameId")
    if "competitionQuery" in config:
        if not isinstance(name, str) or not name.strip() or len(name) > 120 or "gameId" in config or "code" in config:
            raise ValueError("Use an exact competition name, or supply a gameId and any passcode.")
        name = name.strip()
    elif not is_uuid(game_id):
        raise ValueError("Set gameId or competitionQuery.")
    symbol = args.symbol.strip().upper() if args.symbol else None
    if symbol and not re.fullmatch(r"[A-Z0-9][A-Z0-9.-]{0,19}", symbol):
        raise ValueError("Choose a valid symbol for the quote check.")

    opener = build_opener(NoRedirect())

    def request(path, body=None, token=None, timeout=20):
        headers = {"Accept": "application/json"}
        if token:
            headers["Authorization"] = "Bearer " + token
        if body is not None:
            headers["Content-Type"] = "application/json"
        req = Request(origin + path, data=None if body is None else json.dumps(body).encode(), headers=headers)
        try:
            with opener.open(req, timeout=timeout) as response:
                return json.load(response)
        except HTTPError as error:
            with error:
                try:
                    detail = json.load(error)
                except (ValueError, OSError):
                    detail = None
            raise ApiError(error.code, detail) from None

    resumed = args.state.exists()
    if resumed:
        args.state.chmod(0o600)
        state = json.loads(args.state.read_text(encoding="utf-8"))
        matches = state.get("competitionQuery") == name if name else state.get("gameId") == game_id
        if (state.get("version") != 1 or state.get("ownedBotId") is not None or state.get("baseUrl") != origin
                or not matches or not is_uuid(state.get("gameId")) or not is_uuid(state.get("applicationId"))):
            raise ValueError("The state file belongs to another site or competition.")
    else:
        if name:
            filters = urlencode(dict(q=name, botsAllowed="true", registrationOpen="true", automaticApproval="true", noPasscode="true"))
            found = request("/api/competitions?" + filters)
            games = found.get("games")
            if found.get("total") != 1 or not isinstance(games, list) or len(games) != 1:
                raise ValueError("Choose one eligible gameId from competition discovery.")
            game = games[0]
            if (not isinstance(game.get("name"), str) or game["name"].lower() != name.lower()
                    or not is_uuid(game.get("id")) or game.get("participants") not in {"bot", "both"}
                    or game.get("registrationOpen") is not True or game.get("automaticApproval") is not True
                    or game.get("requiresPasscode") is not False):
                raise ValueError("Discovery did not confirm an eligible competition with that exact name.")
            game_id = game["id"]
        state = {"version": 1, "baseUrl": origin, "gameId": game_id, "applicationId": str(uuid.uuid4()),
                 "bot": create_key(), "operator": create_key()}
        if name:
            state["competitionQuery"] = name
        save(args.state, state)

    signing_key = load_key(state["bot"])

    def signed(action, **fields):
        payload = {"action": action, "applicationId": state["applicationId"], "publicKey": public_key(signing_key),
                   "nonce": str(uuid.uuid4()), "timestamp": time.time_ns() // 1_000_000, **fields}
        raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
        message = b"FundClash bot admission v1\n" + raw
        envelope = {"payload": base64.b64encode(raw).decode("ascii"), "signature": signing_key.sign(message).hex()}
        if action == "apply":
            envelope["operatorSignature"] = load_key(state["operator"]).sign(message).hex()
        return request("/api/bot-applications", envelope, timeout=30 if action == "apply" else 15)

    application = None
    try:
        if resumed:
            try:
                application = signed("status")
            except ApiError as error:
                if error.status != 404 or error.body.get("code") != "NOT_FOUND" or state.get("application"):
                    raise
        if application is None:
            application = signed("apply", gameId=state["gameId"], operatorKey=state["operator"]["publicKey"],
                                 disclosure=config["disclosure"], code=config.get("code", ""))
    except Exception as error:
        raise RuntimeError(f"{error} Use the same state file to check status and resume.") from None

    record = application.get("application") or {}
    status, bot_id, identity_id = record.get("status"), application.get("botId"), application.get("identityId")
    if (record.get("id") != state["applicationId"] or not is_uuid(identity_id)
            or application.get("canonicalProfileUrl") != "/agents/" + identity_id
            or status == "approved" and (not is_uuid(bot_id) or record.get("bot_id") != bot_id
                                         or application.get("profileUrl") != "/bots/" + bot_id)):
        raise ValueError("The application was not confirmed. Keep the same state file.")
    if status not in {"approved", "pending"}:
        raise ValueError(f"Application is {status}. Contact the competition host.")
    state.update(application=record, botId=bot_id, identityId=identity_id,
                 canonicalProfileUrl=application["canonicalProfileUrl"], profileUrl=application.get("profileUrl"))
    save(args.state, state)
    result = {"status": "pending", "applicationId": record["id"], "gameId": state["gameId"],
              "identityId": identity_id, "canonicalProfileUrl": origin + state["canonicalProfileUrl"]}
    if status == "pending":
        print(json.dumps({**result, "message": "Run the same command after the host approves the application."}, indent=2))
        return

    if not state.get("token"):
        if state.get("keyRequestPending"):
            raise ValueError("The key reply is uncertain. Ask the host to revoke the uncertain credential before retrying.")
        state["keyRequestPending"] = True
        save(args.state, state)
        try:
            issued = signed("key")
        except ApiError as error:
            if error.status in {400, 401, 403, 404, 409, 413, 415, 422, 429}:
                state["keyRequestPending"] = False
                save(args.state, state)
            raise
        if not re.fullmatch(r"fc_[a-f0-9]{64}", issued.get("token") or "") or not is_uuid((issued.get("key") or {}).get("id")):
            raise ValueError("The key reply is uncertain. Keep the state file and contact the host.")
        state.update(token=issued["token"], key=issued["key"], keyRequestPending=False)
        save(args.state, state)
    token = state["token"]
    if not re.fullmatch(r"fc_[a-f0-9]{64}", token):
        raise ValueError("The saved trading token is invalid.")
    publication = signed("profile", published=publish)
    if publication.get("botId") != bot_id or publication.get("published") is not publish:
        raise ValueError("The bot profile change was not confirmed.")
    state["published"] = publish
    save(args.state, state)
    result.update(status="ready", botId=bot_id, profileUrl=origin + "/bots/" + bot_id, published=publish)
    try:
        portfolio = request("/api/bot/portfolio?view=balances", token=token)
        if not isinstance(portfolio, dict) or portfolio.get("competitionId") != state["gameId"]:
            raise ValueError("Portfolio did not match the chosen competition.")
        result["portfolio"] = portfolio
        if symbol:
            check = request("/api/bot/status?" + urlencode({"symbol": symbol}), token=token)
            competition = check.get("competition") if isinstance(check, dict) else None
            if not isinstance(competition, dict) or competition.get("id") != state["gameId"]:
                raise ValueError("Quote check did not match the chosen competition.")
            prices = check.get("priceService")
            if not isinstance(prices, dict):
                raise ValueError("The quote check was incomplete.")
            result["preflight"] = check
            if prices.get("status") != "available":
                result["checkError"] = {"error": prices.get("error", "No quote was available."),
                                        "code": prices.get("code"), "retryable": prices.get("retryable", False)}
    except ApiError as error:
        result["checkError"] = {"error": str(error), "code": error.body.get("code"),
                                "retryable": error.body.get("retryable", error.status == 429 or error.status >= 500)}
    except (OSError, HTTPException):
        result["checkError"] = {"error": "Could not reach Fundclash. Rerun with the same state file.", "retryable": True}
    except ValueError as error:
        result["checkError"] = {"error": str(error), "retryable": False}
    print(redact(json.dumps(result, indent=2)))
    if "checkError" in result:
        sys.exit(1)


def redact(value):
    return re.sub(r"fc_[a-fA-F0-9]{64}", "[redacted]", value)


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