"""Run on the owner's Mac. SIWC loopback OAuth; secure import over existing SSH."""
import base64
import hashlib
import json
import os
import secrets
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path

import jwt

AUTH = 'https://auth.openai.com'
RESOURCE = 'https://api.openai.com/v1'
ROOT = Path.home()/'.achon'/'openai-connect'
ROOT.mkdir(parents=True, exist_ok=True, mode=0o700)


def remote(action, value=None):
    run = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', 'achon-ada',
        'docker exec -i achon-assistant-assistant-1 /app/.venv/bin/python -m app.chatgpt_admin ' + action],
        input=json.dumps(value or {}), text=True, capture_output=True)
    if run.returncode:
        raise RuntimeError('Could not access the Achon ChatGPT connection service over SSH.')
    return json.loads(run.stdout)


def fetch_json(url, fields=None):
    body = urllib.parse.urlencode(fields).encode() if fields is not None else None
    request = urllib.request.Request(url, data=body, headers={'Accept': 'application/json'})
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.load(response)


def verify_identity(token, issued, nonce, saved, jwks_uri):
    if jwks_uri != AUTH + '/.well-known/jwks.json':
        raise RuntimeError('Unexpected OpenAI signing key endpoint.')
    signing_key = jwt.PyJWKClient(jwks_uri).get_signing_key_from_jwt(token)
    claims = jwt.decode(token, signing_key.key, algorithms=['RS256'], audience=issued,
        issuer=AUTH, leeway=5, options={'require': ['sub', 'exp', 'iat', 'nonce']})
    if not secrets.compare_digest(claims['nonce'], nonce):
        raise RuntimeError('Authorization nonce did not match.')
    if saved.get('client_id') == issued and saved.get('subject') and saved['subject'] != claims['sub']:
        raise RuntimeError('The authorized account does not match the selected registration.')
    return claims


def main():
    # The VM owns refreshes. No access/refresh token is retained on the Mac.
    saved = remote('prepare')
    pending_path = ROOT/'pending-registration.json'
    pending = json.loads(pending_path.read_text()) if pending_path.exists() else {}
    if '--new' in sys.argv:
        saved = { 'host_id': saved['host_id'] }
        pending = {}
    client_id = pending.get('client_id') or saved.get('client_id') or 'dynamic_agent_client'
    state, nonce, verifier = (secrets.token_urlsafe(32) for _ in range(3))
    challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b'=').decode()
    result = {}

    class Callback(BaseHTTPRequestHandler):
        def log_message(self, *args):
            pass  # Callback query contains an authorization code.

        def do_GET(self):
            parsed = urllib.parse.urlsplit(self.path)
            query = urllib.parse.parse_qs(parsed.query)
            valid = parsed.path == '/auth/callback' and len(query.get('state', [])) == 1 and secrets.compare_digest(query['state'][0], state)
            if not valid:
                self.send_error(400, 'Invalid authorization attempt')
                return
            result.update(query)
            self.send_response(200)
            self.send_header('Content-Type', 'text/plain; charset=utf-8')
            self.send_header('Cache-Control', 'no-store')
            self.send_header('Referrer-Policy', 'no-referrer')
            self.end_headers()
            self.wfile.write(b'Authorization received. Return to the Achon connection window to see the result.')

    with HTTPServer(('127.0.0.1', 0), Callback) as server:
        callback = f'http://127.0.0.1:{server.server_port}/auth/callback'
        fields = {'client_id': client_id, 'ext_agent_host_id': saved['host_id'],
            'response_type': 'code', 'redirect_uri': callback,
            'scope': 'openid profile email offline_access resource.invoke chatgpt.tokens.use.direct',
            'resource': RESOURCE, 'state': state, 'nonce': nonce,
            'code_challenge_method': 'S256', 'code_challenge': challenge}
        if client_id == 'dynamic_agent_client':
            fields['agent_name_hint'] = 'Achon'
        elif saved.get('email'):
            fields['login_hint'] = saved['email']
        discovery = fetch_json(AUTH + '/.well-known/openid-configuration')
        if discovery.get('issuer') != AUTH or discovery.get('authorization_endpoint') != AUTH + '/api/accounts/authorize':
            raise RuntimeError('Unexpected OpenAI authorization configuration.')
        print('Opening OpenAI. Sign in and allow Achon to use your ChatGPT plan. This window waits up to 10 minutes.', flush=True)
        webbrowser.open(discovery['authorization_endpoint'] + '?' + urllib.parse.urlencode(fields))
        server.timeout = 1
        deadline = time.monotonic() + 600
        while not result and time.monotonic() < deadline:
            server.handle_request()
    if not result:
        raise RuntimeError('Sign-in timed out. Run this command again when ready.')
    if 'error' in result:
        raise RuntimeError('OpenAI authorization was not completed. Existing connection is unchanged.')
    for key in ('code',):
        if len(result.get(key, [])) != 1:
            raise RuntimeError('Incomplete authorization response.')
    returned = result.get('client_id', [client_id])
    if len(returned) != 1 or not returned[0].startswith('oaiapp_'):
        raise RuntimeError('No issued ChatGPT client ID was returned.')
    issued = returned[0]
    if client_id != 'dynamic_agent_client' and issued != client_id:
        raise RuntimeError('ChatGPT returned a different client registration.')
    # Retain newly issued client on exchange failure, never an authorization code.
    fd = os.open(pending_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, 'w') as f:
        json.dump({'client_id': issued}, f)
    token_endpoint = discovery.get('token_endpoint')
    if token_endpoint != AUTH + '/api/accounts/oauth/token':
        raise RuntimeError('Unexpected OpenAI token endpoint.')
    tokens = fetch_json(token_endpoint, {'grant_type': 'authorization_code', 'client_id': issued,
        'code': result['code'][0], 'code_verifier': verifier, 'redirect_uri': callback, 'resource': RESOURCE})
    claims = verify_identity(tokens['id_token'], issued, nonce, saved, discovery.get('jwks_uri'))
    scopes = str(tokens.get('scope', '')).split()
    if 'chatgpt.tokens.use.direct' not in scopes:
        raise RuntimeError('ChatGPT plan permission was not granted. No plan connection was activated.')
    if str(tokens.get('token_type', '')).lower() != 'bearer' or not tokens.get('access_token'):
        raise RuntimeError('Invalid ChatGPT token response.')
    record = {k: tokens[k] for k in ('access_token', 'refresh_token', 'id_token') if k in tokens}
    record.update(client_id=issued, subject=claims['sub'], email=claims.get('email', ''), issuer=AUTH,
        scopes=scopes, expires_at=time.time() + int(tokens.get('expires_in', 3600)))
    remote('import', record)
    pending_path.unlink(missing_ok=True)
    print('Connected securely to Achon. Open Settings → Connections → OpenAI, select Refresh, then enable Use ChatGPT plan.', flush=True)
    webbrowser.open('https://chat.achon.co/settings/connections/openai')


if __name__ == '__main__':
    try:
        main()
    except Exception as exc:
        # Provider responses and HTTP exception URLs must never enter terminal logs.
        print(str(exc) if isinstance(exc, RuntimeError) else 'Sign-in failed (' + type(exc).__name__ + '). Run the connection command again.', file=sys.stderr)
        sys.exit(1)
