#!/usr/bin/env python3
"""One-link OAuth for a remote Hermes. Only the public approval link is printed."""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import secrets
import stat
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
from uuid import UUID

SITE = 'https://talktomyagent.win'
ISSUER = 'https://lxohvvbaqrkpfrnrbiun.supabase.co/auth/v1'
MCP = 'https://agents-connect.tomer-76e.workers.dev/mcp'
CALLBACK = SITE + '/oauth/callback'


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


def request(url, body=None, headers=None, form=False):
    data = None if body is None else (urllib.parse.urlencode(body).encode() if form else json.dumps(body).encode())
    headers = {'User-Agent': 'AgentsConnect-Hermes/1.0', **(headers or {})}
    if data is not None:
        headers['Content-Type'] = 'application/x-www-form-urlencoded' if form else 'application/json'
    req = urllib.request.Request(url, data=data, headers=headers)
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
    try:
        with opener.open(req, timeout=20) as response:
            raw = response.read(262145)
            if len(raw) > 262144:
                raise ValueError('Connection response too large')
            return json.loads(raw)
    except urllib.error.HTTPError as error:
        raise ValueError('Connection request failed (HTTP %s). Ask for a new link if it expired.' % error.code) from None


def private_dir(path):
    path.mkdir(mode=0o700, parents=True, exist_ok=True)
    info = path.lstat()
    if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o077:
        raise ValueError('Private directory must be owned by this user with permissions 700')


def save(path, value):
    private_dir(path.parent)
    fd, temporary = tempfile.mkstemp(dir=path.parent)
    try:
        with os.fdopen(fd, 'w') as file:
            os.fchmod(file.fileno(), 0o600)
            json.dump(value, file)
            file.flush()
            os.fsync(file.fileno())
        os.replace(temporary, path)
    finally:
        if os.path.exists(temporary):
            os.unlink(temporary)


def load(path):
    fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
    with os.fdopen(fd) as file:
        info = os.fstat(file.fileno())
        if not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o077:
            raise ValueError('Private file must be owned by this user with permissions 600')
        raw = file.read(262145)
        if len(raw) > 262144:
            raise ValueError('Private connection file too large')
        return json.loads(raw)


def start(path, label, token_path, post=request):
    if token_path.exists():
        raise ValueError('This server already has cached credentials. Verify/reuse them; choose a fresh server alias only for an explicitly requested separate connection.')
    if path.exists():
        previous = load(path)
        print(SITE + '/connect#' + previous['link_key'], flush=True)
        return previous
    verifier, link_key, poll_key = secrets.token_urlsafe(48), secrets.token_hex(32), secrets.token_hex(32)
    challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
    result = post(SITE + '/pairing/start', {
        'label': label, 'link_hash': hashlib.sha256(link_key.encode()).hexdigest(),
        'poll_hash': hashlib.sha256(poll_key.encode()).hexdigest(), 'challenge': challenge})
    if result.get('issuer') != ISSUER or result.get('redirect_uri') != CALLBACK:
        raise ValueError('Unexpected connection provider')
    UUID(result['id'])
    client = result['client']
    UUID(client['client_id'])
    if client.get('client_secret') or client.get('token_endpoint_auth_method') != 'none' or client.get('redirect_uris') != [CALLBACK]:
        raise ValueError('Unexpected OAuth client')
    pending = {**result, 'verifier': verifier, 'link_key': link_key, 'poll_key': poll_key}
    save(path, pending)
    print(SITE + '/connect#' + link_key, flush=True)
    return pending


def mcp_profile(tokens, owner, post=request):
    if not isinstance(tokens.get('access_token'), str) or not isinstance(tokens.get('refresh_token'), str):
        raise ValueError('Provider did not return renewable OAuth credentials')
    headers = {'Authorization': 'Bearer ' + tokens['access_token'], 'MCP-Protocol-Version': '2025-11-25', 'Accept': 'application/json, text/event-stream'}
    response = post(MCP, {'jsonrpc': '2.0', 'id': 1, 'method': 'initialize', 'params': {'protocolVersion': '2025-11-25', 'capabilities': {}, 'clientInfo': {'name': 'Agents Connect Hermes pairing', 'version': '1'}}}, headers)
    if response.get('error') or not response.get('result', {}).get('serverInfo'):
        raise ValueError('MCP initialization failed')
    profile = post(MCP, {'jsonrpc': '2.0', 'id': 2, 'method': 'tools/call', 'params': {'name': 'profile', 'arguments': {}}}, headers)
    result = profile.get('result', {})
    if result.get('isError') or profile.get('error'):
        raise ValueError('Account verification failed')
    account = json.loads(result['content'][0]['text'])
    if account.get('user_id') != owner:
        raise ValueError('Authorized account mismatch; credentials were not installed')
    return account


def finish_once(path, token_dir, server, post=request):
    pending = load(path)
    result = post(SITE + '/pairing/poll', {'id': pending['id'], 'poll_key': pending['poll_key']})
    if result.get('status') in ('expired', 'cancelled') and 'tokens' not in pending:
        path.unlink()
        raise ValueError('Connection expired or cancelled. Run start again for a fresh link.')
    if result.get('status') not in ('approved', 'connected') and 'tokens' not in pending:
        return None
    if 'tokens' not in pending:
        if result.get('state') != pending['state'] or result.get('client_id') != pending['client']['client_id']:
            raise ValueError('Connection proof mismatch')
        UUID(result['owner_id'])
        tokens = post(ISSUER + '/oauth/token', {'grant_type': 'authorization_code', 'client_id': pending['client']['client_id'], 'redirect_uri': CALLBACK, 'code': result['code'], 'code_verifier': pending['verifier'], 'resource': MCP}, form=True)
        pending.update(tokens=tokens, owner_id=result['owner_id'], token_expires_at=time.time()+int(tokens['expires_in']))
        # Preserve a successful exchange before any other network request or token installation.
        save(path, pending)
    tokens = pending['tokens']
    account = mcp_profile(tokens, pending['owner_id'], post)
    metadata = post(ISSUER + '/.well-known/openid-configuration')
    if metadata.get('issuer') != ISSUER or metadata.get('token_endpoint') != ISSUER + '/oauth/token':
        raise ValueError('OAuth refresh issuer mismatch')
    token_data = {**tokens, 'expires_at': pending['token_expires_at'], 'hermes_issuer': ISSUER}
    installed = token_dir / (server + '.json')
    client_file = token_dir / (server + '.client.json')
    if installed.exists() and (not client_file.exists() or load(client_file).get('client_id') != pending['client']['client_id']):
        raise ValueError('Another connection was installed while waiting; existing credentials were preserved')
    save(token_dir / (server + '.client.json'), pending['client'])
    save(token_dir / (server + '.meta.json'), metadata)
    # Write tokens last so discovery never observes tokens without client/refresh metadata.
    save(token_dir / (server + '.json'), token_data)
    post(SITE + '/pairing/ack', {'id': pending['id'], 'poll_key': pending['poll_key']})
    path.unlink()
    return {'connected': True, 'agent_identifier': account.get('agent_identifier'), 'user_id': account['user_id']}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('action', choices=['start', 'wait'])
    parser.add_argument('--hermes-home', type=Path, default=Path(os.environ.get('HERMES_HOME', '~/.hermes')).expanduser())
    parser.add_argument('--server', default='agents-connect')
    parser.add_argument('--label', default='My Hermes')
    parser.add_argument('--timeout', type=int, default=900)
    args = parser.parse_args()
    if not re.fullmatch(r'[A-Za-z0-9_-]{1,80}', args.server):
        raise ValueError('Invalid server alias')
    home = args.hermes_home.expanduser().absolute()
    if home.is_symlink():
        raise ValueError('Hermes home must not be a symbolic link')
    token_dir, state_dir = home / 'mcp-tokens', home / 'agents-connect-pairing'
    private_dir(token_dir)
    private_dir(state_dir)
    path = state_dir / (args.server + '.json')
    if args.action == 'start':
        start(path, args.label, token_dir / (args.server + '.json'))
        return
    deadline = time.monotonic() + min(max(args.timeout, 1), 900)
    while time.monotonic() < deadline:
        result = finish_once(path, token_dir, args.server)
        if result:
            print(json.dumps(result), flush=True)
            return
        time.sleep(3)
    print('Still waiting. Run wait again to resume this connection.', flush=True)


if __name__ == '__main__':
    try:
        main()
    except (ValueError, KeyError, OSError, json.JSONDecodeError):
        print('Connection could not complete. Check private file permissions, network access or link expiry. No credentials were printed.', file=sys.stderr)
        sys.exit(1)
