#!/usr/bin/env python3
"""Get a Redplug Media connection key and store it, without printing it.

For AI agents setting up Redplug Media. Without --email the key is anonymous: nothing personal is sent, so no
consent is needed and no person has to be involved. With --email (or --name) the user must first agree to the privacy
notice (agent-setup.json connection_key.privacy_notice). Python 3.8+, standard library only.

    python3 redplug-media-key.py [--claude-code] [--replace]                       anonymous key
    python3 redplug-media-key.py --email you@example.com --agree [--name "Name"]   key tied to an email

  --email, --name  only when the user wants the key tied to them; then --agree is required
  --agree        the user agreed to the privacy notice
  --claude-code  also install (or update) the Claude Code plugin and check that Claude Code connects with the key
  --replace      ask for a new key even though {ENV_VAR} is already set
  --no-verify    skip the connection check (by default the key calls server_status over MCP once)

The key goes straight from the server into the shell profile (macOS/Linux: the line `export {ENV_VAR}=...` in
~/.zshrc, ~/.bashrc or fish's conf.d; Windows: setx). Every client reads it from there: the Claude Code plugin, the
Codex plugin and OpenClaw. The key is never a command argument. Output is one JSON object without the key: what was
stored where, what was checked, and what to do next; ok is false when any step failed. Values in UPPER_CASE between
double underscores are filled in when the file is published (Redplug-Media/clients/build.py).
"""
import argparse
import json
import os
from pathlib import Path
import platform
import re
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.request

ISSUE_URL = 'https://ai.redplug.co.kr/v2/keys'
MCP_URL = 'https://ai.redplug.co.kr/v2/mcp'
SETUP_GUIDE = 'https://www.redplug.co.kr/plugin-service/'
ENV_VAR = 'REDPLUG_MEDIA_KEY'
PRIVACY_VERSION = '2026-11-27'
PLUGIN = 'redplug-media@redplug'
MARKETPLACE_REPO = 'azossy/redplug-media-plugins'
MARKETPLACE = 'redplug'
SERVER = 'redplug-media'
TIMEOUT_SECONDS = 15
ATTEMPTS = 3
RETRY_PAUSE_SECONDS = 2
COMMAND_TIMEOUT_SECONDS = 180
MCP_PROTOCOL = '2025-06-18'
MCP_ACCEPT = 'application/json, text/event-stream'
WELCOME = 'media_guide(kind="overview", topic="welcome")'
SHOWN_KEY_CHARS = 4
EXIT_INPUT, EXIT_SERVER, EXIT_STORE, EXIT_CLIENT = 2, 3, 4, 5


def report(ok, exit_code=0, **fields):
    print(json.dumps({'ok': ok, **fields}, ensure_ascii=False, indent=2))
    sys.exit(exit_code)


def request_key(email, name, consent, locale):
    fields = {'privacy_consent': consent, 'locale': locale}
    if email:
        fields['email'] = email
    if name:
        fields['name'] = name
    body = json.dumps(fields).encode()
    for attempt in range(1, ATTEMPTS + 1):
        request = urllib.request.Request(ISSUE_URL, data=body, method='POST', headers={
            'Content-Type': 'application/json', 'Accept-Language': locale, 'User-Agent': 'redplug-media-key'})
        try:
            with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
                return json.loads(response.read())
        except urllib.error.HTTPError as error:
            # the server's answer (input, rate limit, unavailable) is final: no retry
            try:
                detail = json.loads(error.read()).get('error', {})
            except (ValueError, AttributeError):
                detail = {'code': f'HTTP {error.code}'}
            report(False, EXIT_SERVER, error=detail, retry_after=error.headers.get('Retry-After'))
        except (urllib.error.URLError, TimeoutError, OSError) as error:
            if attempt == ATTEMPTS:
                report(False, EXIT_SERVER, error={'code': 'NETWORK', 'message': type(error).__name__,
                                                  'guidance': 'Check the internet connection and try again later.'})
            time.sleep(RETRY_PAUSE_SECONDS * attempt)
    return None


def mcp_message(raw):
    """A JSON-RPC message from a plain JSON body or from server-sent events (the last data line wins)."""
    text = raw.decode('utf-8', 'replace').strip()
    if text.startswith('{'):
        return json.loads(text)
    data = [line[5:].strip() for line in text.splitlines() if line.startswith('data:')]
    return json.loads(data[-1]) if data else {}


def verify(mcp_url, key, locale):
    """Call server_status once with the new key over streamable HTTP; returns what the server reported."""
    session = None

    def post(payload):
        nonlocal session
        headers = {'Content-Type': 'application/json', 'Accept': MCP_ACCEPT, 'Authorization': f'Bearer {key}',
                   'MCP-Protocol-Version': MCP_PROTOCOL, 'User-Agent': 'redplug-media-key'}
        if session:
            headers['Mcp-Session-Id'] = session
        request = urllib.request.Request(mcp_url, data=json.dumps(payload).encode(), method='POST', headers=headers)
        with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
            session = response.headers.get('Mcp-Session-Id') or session
            raw = response.read()
            return mcp_message(raw) if raw.strip() else {}

    try:
        post({'jsonrpc': '2.0', 'id': 1, 'method': 'initialize', 'params': {
            'protocolVersion': MCP_PROTOCOL, 'capabilities': {}, 'clientInfo': {'name': 'redplug-media-key', 'version': '1'}}})
        post({'jsonrpc': '2.0', 'method': 'notifications/initialized'})
        answer = post({'jsonrpc': '2.0', 'id': 2, 'method': 'tools/call',
                       'params': {'name': 'server_status', 'arguments': {'locale': locale}}})
        # the introduction for the user, so the agent can present it before its client loads the new tools
        welcome = post({'jsonrpc': '2.0', 'id': 3, 'method': 'tools/call', 'params': {
            'name': 'media_guide', 'arguments': {'kind': 'overview', 'topic': 'welcome', 'locale': locale}}})
    except urllib.error.HTTPError as error:
        return {'ok': False, 'http_status': error.code}
    except (urllib.error.URLError, TimeoutError, OSError, ValueError) as error:
        return {'ok': False, 'error': type(error).__name__}
    status = (answer.get('result') or {}).get('structuredContent') or {}
    guide = (welcome.get('result') or {}).get('structuredContent') or {}
    # ok: the key was accepted and the server answered; ready: every part of it can take work right now
    return {'ok': bool(status), 'ready': bool(status.get('ready')), 'version': status.get('version'),
            'kinds': status.get('kinds'), 'message': status.get('message'), 'welcome': guide.get('content')}


def shell_profile():
    shell = Path(os.environ.get('SHELL', '')).name
    home = Path.home()
    if shell == 'fish':
        return home / '.config' / 'fish' / 'conf.d' / 'redplug-media.fish', 'fish'
    if shell == 'bash':
        return (home / ('.bash_profile' if platform.system() == 'Darwin' else '.bashrc')), 'sh'
    return home / '.zshrc', 'sh'


def store_unix(key):
    path, kind = shell_profile()
    line = f'set -gx {ENV_VAR} {key}' if kind == 'fish' else f'export {ENV_VAR}={key}'
    pattern = re.compile(rf'^\s*(export\s+{ENV_VAR}=|set\s+-gx\s+{ENV_VAR}\s)')
    lines = path.read_text(encoding='utf-8').splitlines() if path.is_file() else []
    kept = [existing for existing in lines if not pattern.match(existing)]
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text('\n'.join(kept + [line]) + '\n', encoding='utf-8')
    return str(path).replace(str(Path.home()), '~', 1)


def store_windows(key):
    result = subprocess.run(['setx', ENV_VAR, key], capture_output=True, timeout=COMMAND_TIMEOUT_SECONDS)
    if result.returncode != 0:
        report(False, EXIT_STORE, error={'code': 'SETX', 'message': 'setx failed'})
    return f'user environment variable {ENV_VAR} (setx)'


def run(command, env=None):
    """Run a CLI command without a shell. Returns (ok, stdout, last line of the output for the report)."""
    try:
        result = subprocess.run(command, capture_output=True, text=True, timeout=COMMAND_TIMEOUT_SECONDS, env=env)
    except (OSError, subprocess.SubprocessError) as error:
        return False, '', type(error).__name__
    lines = (result.stderr or result.stdout).strip().splitlines()
    return result.returncode == 0, result.stdout, (lines[-1] if lines else f'exit {result.returncode}')


def installed_plugin(claude):
    ok, out, _ = run([claude, 'plugin', 'list', '--json'])
    try:
        return next((p for p in json.loads(out) if p.get('id') == PLUGIN), None) if ok else None
    except ValueError:
        return None


def setup_claude_code(key):
    """Install or update the plugin, enable it, then let Claude Code itself connect with the key (claude mcp list).
    Returns (ok, details); success is only reported when Claude Code shows the server as connected."""
    claude = shutil.which('claude')
    if not claude:
        return False, {'error': 'claude CLI not found on PATH'}
    run([claude, 'plugin', 'marketplace', 'add', MARKETPLACE_REPO])
    present = installed_plugin(claude)
    if present:
        run([claude, 'plugin', 'marketplace', 'update', MARKETPLACE])
        step = run([claude, 'plugin', 'update', PLUGIN, '--scope', present.get('scope') or 'user'])
    else:
        step = run([claude, 'plugin', 'install', PLUGIN, '--scope', 'user'])
    present = installed_plugin(claude)
    if not present:
        return False, {'error': f'plugin not installed: {step[2]}'}
    if not present.get('enabled'):
        run([claude, 'plugin', 'enable', PLUGIN])
        present = installed_plugin(claude) or present
    environment = dict(os.environ, **{ENV_VAR: key})
    _, listing, last = run([claude, 'mcp', 'list'], env=environment)
    line = next((l.strip() for l in listing.splitlines() if l.strip().startswith(f'plugin:{SERVER}:{SERVER}')), '')
    connected = 'Connected' in line and bool(present.get('enabled'))
    details = {'plugin_version': present.get('version'), 'enabled': bool(present.get('enabled')),
               'mcp_list': line.split(' - ', 1)[-1] if line else f'server not listed ({last})'}
    return connected, details


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument('--email')
    parser.add_argument('--name')
    parser.add_argument('--agree', action='store_true')
    parser.add_argument('--claude-code', action='store_true')
    parser.add_argument('--replace', action='store_true')
    parser.add_argument('--locale', default='ko')
    parser.add_argument('--no-verify', action='store_true')
    args = parser.parse_args()
    personal = bool((args.email or '').strip() or (args.name or '').strip())
    if personal and not args.agree:
        report(False, EXIT_INPUT, error={'code': 'CONSENT', 'message': 'An email or name needs the user\'s agreement to the privacy notice.',
                                         'guidance': f'Show the privacy notice (version {PRIVACY_VERSION}) and run again with --agree only after the user agrees, '
                                                     'or leave out --email and --name for an anonymous key.'})
    existing = os.environ.get(ENV_VAR, '').strip()
    stored, answer = [], {}
    if existing and not args.replace:
        if not args.claude_code:
            report(True, already_set=True, message=f'{ENV_VAR} is already set; no new key was requested.',
                   next='Use the existing key, or run again with --replace for a new one (jobs of the old key stay with it). '
                        'Add --claude-code to install the Claude Code plugin with it.')
        key = existing
    else:
        answer = request_key((args.email or '').strip() or None, (args.name or '').strip() or None, personal, args.locale) or {}
        key = answer.get('key', '')
        if not key:
            report(False, EXIT_SERVER, error={'code': 'NO_KEY', 'message': 'The server answered without a key.'})
        stored.append(store_windows(key) if os.name == 'nt' else store_unix(key))
    fields = {'stored_in': stored, 'key_hint': f'…{key[-SHOWN_KEY_CHARS:]}', 'env_var': ENV_VAR,
              'new_key': bool(answer), 'anonymous': not personal if answer else None}
    mcp_url = answer.get('mcp_url') or MCP_URL
    checked = None if args.no_verify else verify(mcp_url, key, args.locale)
    fields.update(verified=checked, mcp_url=mcp_url, setup_guide=answer.get('setup_guide') or SETUP_GUIDE)
    if checked is not None and not checked.get('ok'):
        report(False, EXIT_SERVER, **fields, error={'code': 'VERIFY', 'message': 'The server did not accept the key or did not answer.',
                                                   'guidance': 'See verified (http_status 401: the key was revoked, run again with '
                                                               '--replace; otherwise the server may be busy or down, try later).'})
    if args.claude_code:
        connected, details = setup_claude_code(key)
        fields['claude_code'] = details
        if not connected:
            report(False, EXIT_CLIENT, **fields, error={
                'code': 'CLAUDE_CODE', 'message': 'Claude Code did not connect to the server with the plugin.',
                'guidance': 'See claude_code. The key is stored; install by hand with clients.claude-code.install, then '
                            'check with clients.claude-code.verify.'})
    report(True, **fields,
           next=f'Finish the client setup, then tell the user what Redplug Media can do: present verified.welcome (or {WELCOME}) '
                f'in their language. Apps that were already running read {ENV_VAR} only after a restart: a new Claude Code '
                'session started from a new terminal (the Claude desktop app: quit and reopen it), the Codex app, the OpenClaw '
                'Gateway. Never print the key.')


if __name__ == '__main__':
    main()
