import requests
import webbrowser
import os
from urllib.parse import urlencode
from http.server import HTTPServer, BaseHTTPRequestHandler
from tools.get_server_token import GetServerTokenForDiscord

# Disable stderr output
os.environ['PYTHONWARNINGS'] = 'ignore'

REDIRECT_URI = "http://localhost:5000/callback"
SCOPES = ["identify"]
CLIENT_ID = "1240007913175781508"
AUTENTICATION_SUCCESS_MESSAGE = """
                <html>
                <head>
                    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
                    <meta content="utf-8" http-equiv="encoding">
                </head>
                    <body>
                        <h1>Authentication réussie</h1>
                        <p>Vous pouvez maintenant fermer cette fenêtre et revenir au launcher de La Tanière.</p>
                        </body>
                </html>
            """.encode('utf-8')

class OAuthCallbackHandler(BaseHTTPRequestHandler):
    code: str | None = None

    def do_GET(self):
        if "/callback" in self.path:
            query = self.path.split("?")[1]
            params = dict(p.split("=") for p in query.split("&"))
            OAuthCallbackHandler.code = params.get("code")

            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            self.wfile.write(AUTENTICATION_SUCCESS_MESSAGE)

# return discord application id (client id)
def get_discord_client_id() -> str:
    return CLIENT_ID

# return discord user id
def get_discord_user_id() -> str:
    # récupération des infos serveur lataupe
    session_id = GetServerTokenForDiscord.authenticate()
    client_secret = GetServerTokenForDiscord.get_token(session_id)

    auth_url = "https://discord.com/api/oauth2/authorize"
    params = {
        "client_id": CLIENT_ID,
        "redirect_uri": REDIRECT_URI,
        "response_type": "code",
        "scope": " ".join(SCOPES),
    }

    webbrowser.open(f"{auth_url}?{urlencode(params)}")

    server = HTTPServer(("localhost", 5000), OAuthCallbackHandler)
    # celle ligne cache le stderr output pour ne pas afficher l'url de callback dans la console
    # valable en debug mode
    os.dup2(os.open(os.devnull, os.O_WRONLY), 2)
    server.handle_request()

    if not OAuthCallbackHandler.code:
        raise RuntimeError("OAuth échoué")

    token = requests.post(
        "https://discord.com/api/oauth2/token",
        data={
            "client_id": CLIENT_ID,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": OAuthCallbackHandler.code,
            "redirect_uri": REDIRECT_URI,
        },
        headers={"Content-Type": "application/x-www-form-urlencoded"},
    ).json()

    user = requests.get(
        "https://discord.com/api/users/@me",
        headers={"Authorization": f"Bearer {token['access_token']}"},
    ).json()

    return user["id"]
