#!/usr/bin/env python3
"""Local ChatGPT authorization helper — official SIWC self-hosted VM flow.

Runs on the USER'S device (computer or Termux on Android), NOT on the server:

  python3 tools/chatgpt_connect.py --lab https://asisten.masyamin.biz.id --ticket <TICKET>

What it does (official flow, https://developers.openai.com/siwc/):
  1. POST {lab}/api/chatgpt/import-ticket/info {ticket} -> registration context
     (mode, VM's ext_agent_host_id, issued client_id for reconnect, id_token_hint).
  2. Starts a loopback listener on 127.0.0.1:<port>/auth/callback (never public).
  3. Opens the system browser at the official OpenAI authorize URL
     (Authorization Code + PKCE S256 + fresh state + OIDC nonce).
  4. Validates the returned state, extracts code + issued client_id + scope.
  5. Exchanges the code at the official token endpoint (no client secret).
  6. POSTs the protected credential bundle to {lab}/api/chatgpt/import
     (ticket-authenticated, TLS, JSON body — never URL params).
  7. Prints a summary WITHOUT tokens.

Stdlib only: works with system Python and Termux (pkg install python).
"""
from __future__ import annotations

import argparse
import base64
import hashlib
import json
import secrets
import shutil
import socket
import subprocess
import sys
import threading
import time
import urllib.parse
import urllib.request
import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer

AUTHORIZE_URL = "https://auth.openai.com/api/accounts/authorize"
TOKEN_URL = "https://auth.openai.com/api/accounts/oauth/token"
RESOURCE = "https://api.openai.com/v1"
DYNAMIC_CLIENT_ID = "dynamic_agent_client"
IDENTITY_SCOPES = "openid profile email"
PLAN_SCOPES = "offline_access resource.invoke chatgpt.tokens.use.direct"
FULL_SCOPES = f"{IDENTITY_SCOPES} {PLAN_SCOPES}"
CALLBACK_PATH = "/auth/callback"


def b64url_nopad(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


def pkce_pair() -> tuple[str, str]:
    verifier = secrets.token_urlsafe(64)[:96]
    challenge = b64url_nopad(hashlib.sha256(verifier.encode()).digest())
    return verifier, challenge


def post_json(url: str, payload: dict, timeout: int = 30) -> dict:
    data = json.dumps(payload).encode()
    req = urllib.request.Request(url, data=data,
                                 headers={"Content-Type": "application/json",
                                          "User-Agent": "muse-super-agent/local-helper"},
                                 method="POST")
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return json.loads(r.read().decode())
    except urllib.error.HTTPError as e:
        try:
            body = e.read().decode()[:300]
        except Exception:
            body = ""
        raise RuntimeError(f"HTTP {e.code} from {url}: {body}")


def post_form(url: str, fields: dict, timeout: int = 30) -> dict:
    data = urllib.parse.urlencode(fields).encode()
    req = urllib.request.Request(url, data=data,
                                 headers={"Content-Type": "application/x-www-form-urlencoded",
                                          "User-Agent": "muse-super-agent/local-helper"},
                                 method="POST")
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return json.loads(r.read().decode())
    except urllib.error.HTTPError as e:
        try:
            body = e.read().decode()[:300]
        except Exception:
            body = ""
        raise RuntimeError(f"token endpoint HTTP {e.code}: {body}")


class CallbackHandler(BaseHTTPRequestHandler):
    result: dict | None = None
    expected_state: str = ""

    def log_message(self, *a):
        pass

    def do_GET(self):
        parsed = urllib.parse.urlparse(self.path)
        if parsed.path != CALLBACK_PATH:
            self.send_response(404)
            self.end_headers()
            return
        q = urllib.parse.parse_qs(parsed.query)
        CallbackHandler.result = {k: v[0] for k, v in q.items()}
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.end_headers()
        self.wfile.write(
            b"<html><body style='font-family:sans-serif'>"
            b"<h2>Authorization received</h2>"
            b"<p>You can close this window and return to the terminal.</p>"
            b"</body></html>")


def find_port(preferred: int) -> int:
    for port in [preferred, 1455, 54321, 18080, 18888]:
        with socket.socket() as s:
            try:
                s.bind(("127.0.0.1", port))
                return port
            except OSError:
                continue
    raise RuntimeError("no free loopback port found")


def open_browser(url: str) -> None:
    opened = False
    if shutil.which("termux-open"):
        r = subprocess.run(["termux-open", url], check=False)
        opened = (r.returncode == 0)
    if not opened:
        try:
            opened = bool(webbrowser.open(url))
        except Exception:
            opened = False
    # Always print the URL: on retry rounds the browser sometimes doesn't
    # come to the foreground, and the user needs it for manual opening.
    print("Authorization URL (open manually if the browser didn't open):")
    print(url + "\n")


def authorize_once(host_id: str, redirect_uri: str, port: int,
                   client_id: str, id_token_hint: str = "",
                   agent_name_hint: str = "") -> tuple[str, str, str]:
    """Run one browser authorization round. Returns (code, issued_client_id, scope).

    Raises RuntimeError on timeout/denial/state mismatch/incomplete registration.
    """
    verifier, challenge = pkce_pair()
    state = "st_" + secrets.token_urlsafe(24)
    nonce = "n_" + secrets.token_urlsafe(24)
    CallbackHandler.result = None

    params = {
        "response_type": "code",
        "redirect_uri": redirect_uri,
        "scope": FULL_SCOPES,
        "resource": RESOURCE,
        "state": state,
        "nonce": nonce,
        "code_challenge": challenge,
        "code_challenge_method": "S256",
        "ext_agent_host_id": host_id,
        "client_id": client_id,
    }
    if agent_name_hint:
        params["agent_name_hint"] = agent_name_hint
    if id_token_hint:
        params["id_token_hint"] = id_token_hint

    server = HTTPServer(("127.0.0.1", port), CallbackHandler)
    server.timeout = 1
    stop = threading.Event()

    def serve():
        while not stop.is_set():
            server.handle_request()
            if CallbackHandler.result is not None:
                stop.set()

    t = threading.Thread(target=serve, daemon=True)
    t.start()
    open_browser(AUTHORIZE_URL + "?" + urllib.parse.urlencode(params))
    t.join(timeout=600)
    server.server_close()

    res = CallbackHandler.result
    if res is None:
        raise RuntimeError("timed out waiting for the browser callback")
    if res.get("error"):
        raise RuntimeError(
            f"authorization denied/failed: {res.get('error')} "
            f"{res.get('error_description', '')}".strip())
    if res.get("state") != state:
        raise RuntimeError(
            "state mismatch — this callback URL belongs to a different "
            "attempt. Finish the authorization in the CURRENT run instead of "
            "reusing an old callback URL (each run has a fresh state).")
    code = res.get("code", "")
    issued = res.get("client_id", "")
    if not code:
        raise RuntimeError("no authorization code in callback")
    if not issued or issued == DYNAMIC_CLIENT_ID:
        raise RuntimeError("registration incomplete — no issued client_id in callback")
    return code, issued, res.get("scope", ""), verifier, nonce


def exchange_once(code: str, verifier: str, redirect_uri: str,
                  client_id: str) -> dict:
    return post_form(TOKEN_URL, {
        "grant_type": "authorization_code",
        "client_id": client_id,
        "code": code,
        "code_verifier": verifier,
        "redirect_uri": redirect_uri,
        "resource": RESOURCE,
    })


def main() -> int:
    ap = argparse.ArgumentParser(
        description="Local ChatGPT authorization for the LAB agent (official SIWC flow).")
    ap.add_argument("--lab", required=True,
                    help="LAB base URL, e.g. https://asisten.masyamin.biz.id")
    ap.add_argument("--ticket", required=True, help="one-time import ticket from the LAB UI")
    ap.add_argument("--port", type=int, default=1455, help="preferred loopback port")
    args = ap.parse_args()

    lab = args.lab.rstrip("/")
    if not lab.startswith("https://"):
        print("ERROR: --lab must be an https:// URL (TLS is required).")
        return 2

    print("Requesting registration context from LAB...")
    try:
        ctx = post_json(f"{lab}/api/chatgpt/import-ticket/info",
                        {"ticket": args.ticket})
    except Exception as e:
        print(f"ERROR: cannot use ticket: {e}")
        print("Get a fresh ticket: LAB UI -> Settings -> Connections -> ChatGPT "
              "-> Generate import ticket.")
        return 1
    if not ctx.get("ok"):
        print(f"ERROR: ticket rejected: {ctx.get('output')}")
        return 1

    mode = ctx.get("mode", "new")
    host_id = ctx["host_id"]
    port = find_port(args.port)
    redirect_uri = f"http://127.0.0.1:{port}{CALLBACK_PATH}"

    # First attempt: saved issued client_id (reconnect) or dynamic registration.
    if mode == "reconnect" and ctx.get("client_id"):
        first_client_id, first_hint, first_name_hint = ctx["client_id"], ctx.get("id_token_hint", ""), ""
    else:
        first_client_id, first_hint, first_name_hint = \
            DYNAMIC_CLIENT_ID, "", ctx.get("agent_name_hint", "MuseSuper")

    print(f"\nStarting local OAuth server...\nListening on 127.0.0.1:{port}\n")
    print("Opening OpenAI authorization page...\nWaiting for authorization "
          "(complete it in the browser)...")
    try:
        code, issued, granted_scope, verifier, nonce = authorize_once(
            host_id, redirect_uri, port, first_client_id, first_hint, first_name_hint)
    except RuntimeError as e:
        print(f"\nERROR: {e}")
        return 1
    if mode == "reconnect" and ctx.get("client_id") and issued != ctx["client_id"]:
        print("\nERROR: callback client_id differs from the saved registration — "
              "refusing to overwrite another account's registration.")
        return 1

    print("\nAuthorization successful.\nExchanging authorization code...")
    try:
        tokens = exchange_once(code, verifier, redirect_uri, issued)
    except RuntimeError as e:
        if "invalid_grant" not in str(e) or issued == first_client_id:
            print(f"ERROR: code exchange failed: {e}")
            print("The code may have expired — run this helper again for a fresh one.")
            return 1
        # Official recovery (docs: errors-and-recovery): discard the code and
        # start a FRESH authorization with the issued client ID retained.
        print("First exchange returned invalid_grant — retrying authorization "
              "with the issued client ID (per OpenAI docs)...")
        print("Opening OpenAI authorization page again...")
        try:
            code, issued2, granted_scope, verifier, nonce = authorize_once(
                host_id, redirect_uri, port, issued)
        except RuntimeError as e2:
            print(f"\nERROR: {e2}")
            return 1
        if issued2 != issued:
            print("\nERROR: retry returned a different client_id — aborting.")
            return 1
        print("\nAuthorization successful.\nExchanging authorization code...")
        try:
            tokens = exchange_once(code, verifier, redirect_uri, issued)
        except RuntimeError as e2:
            print(f"ERROR: code exchange failed again: {e2}")
            return 1

    scopes = (tokens.get("scope") or granted_scope or "").split()
    bundle = {
        "issuer": "https://auth.openai.com",
        "client_id": issued,
        "ext_agent_host_id": host_id,
        "id_token": tokens.get("id_token", ""),
        "access_token": tokens.get("access_token", ""),
        "refresh_token": tokens.get("refresh_token", ""),
        "token_type": tokens.get("token_type", "Bearer"),
        "expires_in": tokens.get("expires_in", 3600),
        "scopes": scopes,
        "saved_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "nonce": nonce,
        "redirect_uri": redirect_uri,
    }
    print("Credential obtained.\nConnecting to LAB...\nSecure transfer...")
    try:
        result = post_json(f"{lab}/api/chatgpt/import",
                           {"ticket": args.ticket, "bundle": bundle})
    except Exception as e:
        print(f"ERROR: import failed: {e}")
        print("Tokens were NOT sent anywhere else. Get a fresh ticket and retry — "
              "the OAuth code is single-use, so re-run this helper.")
        return 1
    if not result.get("ok"):
        print(f"ERROR: LAB rejected the import: {result.get('output')}")
        return 1

    print("Secure transfer complete.\nRemote LAB credential installed.\n")
    print(f"ChatGPT connection: OK ({result.get('display_name', '')})")
    plan = (result.get("plan_usage") or "unknown").upper()
    print(f"ChatGPT plan usage: {plan}")
    if plan != "ENABLED":
        print("Note: plan usage is NOT enabled — the agent will keep using the "
              "OpenAI API key for inference. To enable it, re-run with plan "
              "consent approved at the OpenAI page.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
