"""Receive one SyAuth OAuth callback locally for a manual protocol test.

Python 3.8+; no third-party packages. This does not create an application
session, exchange tokens, or validate an OIDC ID token.
"""

import argparse
import base64
import hashlib
import json
import secrets
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlencode, urlsplit


REDIRECT_URI = "http://127.0.0.1:8080/callback"


class CallbackHandler(BaseHTTPRequestHandler):
    def log_message(self, *_args):
        # Do not write authorization codes from request URLs to access logs.
        pass

    def reply(self, status, message):
        body = message.encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "text/plain; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-store")
        self.send_header("Referrer-Policy", "no-referrer")
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        url = urlsplit(self.path)
        if url.path != "/callback":
            self.reply(404, "Use the authorization URL printed in your terminal.")
            return
        query = parse_qs(url.query, keep_blank_values=True)
        states = query.get("state", [])
        if (len(states) != 1 or not states[0].isascii()
                or not secrets.compare_digest(states[0], self.server.expected_state)):
            self.reply(400, "Missing or mismatched state. Callback rejected.")
            return
        codes = query.get("code", [])
        errors = query.get("error", [])
        if not ((len(codes) == 1 and codes[0] and not errors)
                or (len(errors) == 1 and errors[0] and not codes)):
            self.reply(400, "Expected one authorization code or one OAuth error.")
            return
        with self.server.result_lock:
            if self.server.result is not None:
                self.reply(409, "This callback has already been received.")
                return
            self.reply(200, "Callback received and state matched. Return to your terminal.")
            self.server.result = query


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--client-id", required=True, help="Your public OAuth client_id")
    args = parser.parse_args()
    state, nonce, verifier = (secrets.token_hex(32) for _ in range(3))
    challenge = base64.urlsafe_b64encode(
        hashlib.sha256(verifier.encode("ascii")).digest()
    ).rstrip(b"=").decode("ascii")
    params = {
        "client_id": args.client_id,
        "redirect_uri": REDIRECT_URI,
        "response_type": "code",
        "scope": "openid profile email write",
        "state": state,
        "nonce": nonce,
        "code_challenge": challenge,
        "code_challenge_method": "S256",
    }
    try:
        server = ThreadingHTTPServer(("127.0.0.1", 8080), CallbackHandler)
    except OSError as error:
        parser.exit(1, "Cannot listen on 127.0.0.1:8080: %s\n" % error)
    with server:
        server.expected_state = state
        server.result = None
        server.result_lock = threading.Lock()
        server.timeout = 1
        print("Registered redirect URI must be: " + REDIRECT_URI, flush=True)
        print("Open this URL in your browser (leave this terminal running):", flush=True)
        print("https://api.syauth.com/e/v1/oauth/authorize/?" + urlencode(params), flush=True)
        deadline = time.monotonic() + 600
        while server.result is None and time.monotonic() < deadline:
            server.handle_request()
        if server.result is None:
            parser.exit(1, "No valid callback received within 10 minutes. Run a new test.\n")
        if "error" in server.result:
            print("OAuth returned an error (state matched):", flush=True)
            print(json.dumps(server.result, indent=2), flush=True)
            return 1
        print("State matched. Use these values in step 3 of the OAuth guide:", flush=True)
        print(json.dumps({
            "YOUR_PUBLIC_CLIENT_ID": args.client_id,
            "YOUR_AUTHORIZATION_CODE": server.result["code"][0],
            "YOUR_PKCE_CODE_VERIFIER": verifier,
            "YOUR_REDIRECT_URI": REDIRECT_URI,
            "saved_nonce": nonce,
        }, indent=2), flush=True)
        print("Exchange the code promptly and only once. Keep this test output private.")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except KeyboardInterrupt:
        raise SystemExit("Test stopped. Run the script again for a fresh attempt.")
