#!/usr/bin/env python3
"""
MCP Gateway CLI - Workspace Management Tool
"""
import click
import requests
import json
import os
from pathlib import Path
from typing import Optional

# Configuration
CONFIG_DIR = Path.home() / '.mcpgw'
CONFIG_FILE = CONFIG_DIR / 'config.json'
API_BASE = os.getenv('MCPGW_API_URL', 'https://api.mcpgw.io/api/v1')


class Config:
    """CLI configuration manager with profile support"""
    
    def __init__(self):
        self.config_dir = CONFIG_DIR
        self.config_file = CONFIG_FILE
        self._ensure_config_dir()
    
    def _ensure_config_dir(self):
        self.config_dir.mkdir(exist_ok=True)
    
    def load(self) -> dict:
        if not self.config_file.exists():
            return {'profiles': {}, 'current_profile': 'default'}
        return json.loads(self.config_file.read_text())
    
    def save(self, data: dict):
        self.config_file.write_text(json.dumps(data, indent=2))
    
    def get_current_profile(self) -> str:
        """Get active profile name from env or config"""
        # Environment variable takes precedence
        env_profile = os.getenv('MCPGW_PROFILE')
        if env_profile:
            return env_profile
        
        config = self.load()
        return config.get('current_profile', 'default')
    
    def get_profile_data(self, profile: Optional[str] = None) -> dict:
        """Get data for specific profile"""
        if profile is None:
            profile = self.get_current_profile()
        
        config = self.load()
        profiles = config.get('profiles', {})
        return profiles.get(profile, {})
    
    def set_profile_data(self, data: dict, profile: Optional[str] = None):
        """Set data for specific profile"""
        if profile is None:
            profile = self.get_current_profile()
        
        config = self.load()
        if 'profiles' not in config:
            config['profiles'] = {}
        config['profiles'][profile] = data
        self.save(config)
    
    def switch_profile(self, profile: str):
        """Switch active profile"""
        config = self.load()
        config['current_profile'] = profile
        self.save(config)
    
    def list_profiles(self) -> list:
        """List all configured profiles"""
        config = self.load()
        return list(config.get('profiles', {}).keys())
    
    def get_token(self) -> Optional[str]:
        profile_data = self.get_profile_data()
        return profile_data.get('token')
    
    def set_token(self, token: str):
        profile_data = self.get_profile_data()
        profile_data['token'] = token
        self.set_profile_data(profile_data)
    
    def get_api_url(self) -> str:
        """Get API URL from profile or environment"""
        # Environment variable takes precedence
        if os.getenv('MCPGW_API_URL'):
            return os.getenv('MCPGW_API_URL')
        
        profile_data = self.get_profile_data()
        return profile_data.get('api_url', 'https://api.mcpgw.io/api/v1')
    
    def set_api_url(self, api_url: str):
        """Set API URL for current profile"""
        profile_data = self.get_profile_data()
        profile_data['api_url'] = api_url
        self.set_profile_data(profile_data)
    
    def get_workspace(self) -> Optional[str]:
        profile_data = self.get_profile_data()
        return profile_data.get('workspace_id')
    
    def set_workspace(self, workspace_id: str):
        profile_data = self.get_profile_data()
        profile_data['workspace_id'] = workspace_id
        self.set_profile_data(profile_data)
    
    def clear_workspace(self):
        profile_data = self.get_profile_data()
        if 'workspace_id' in profile_data:
            del profile_data['workspace_id']
        self.set_profile_data(profile_data)


config = Config()


def make_request(method: str, endpoint: str, data=None, params=None):
    """Make authenticated API request"""
    token = config.get_token()
    if not token:
        click.echo("❌ Not authenticated. Run 'mcpgw auth login' first.", err=True)
        raise click.Abort()
    
    headers = {'Authorization': f'Bearer {token}'}
    # Use API URL from profile or environment
    api_url = config.get_api_url()
    url = f"{api_url}{endpoint}"
    
    try:
        response = requests.request(
            method, url, 
            json=data, 
            params=params,
            headers=headers
        )
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        click.echo(f"❌ Request failed: {e}", err=True)
        raise click.Abort()


def resolve_workspace_id(identifier: str) -> str:
    """
    Resolve workspace identifier (name, slug, or UUID) to workspace ID.
    
    Args:
        identifier: Workspace name, slug, or UUID
        
    Returns:
        Workspace UUID
        
    Raises:
        click.Abort if workspace not found
    """
    # If it looks like a UUID (contains dashes in UUID format), use it directly
    if '-' in identifier and len(identifier) == 36:
        return identifier
    
    # Otherwise, fetch all workspaces and search by name or slug
    data = make_request('GET', '/workspaces')
    workspaces = data.get('workspaces', [])
    
    # Try exact match on name (case-insensitive)
    identifier_lower = identifier.lower()
    for ws in workspaces:
        if ws['name'].lower() == identifier_lower:
            return ws['id']
    
    # Try exact match on slug
    for ws in workspaces:
        if ws.get('slug', '').lower() == identifier_lower:
            return ws['id']
    
    # Try partial match on name
    matches = [ws for ws in workspaces if identifier_lower in ws['name'].lower()]
    if len(matches) == 1:
        return matches[0]['id']
    elif len(matches) > 1:
        click.echo(f"❌ Multiple workspaces match '{identifier}':")
        for ws in matches:
            click.echo(f"   • {ws['name']} (ID: {ws['id']})")
        click.echo("\n   Please use the full workspace name or UUID")
        raise click.Abort()
    
    # No matches found
    click.echo(f"❌ Workspace '{identifier}' not found")
    raise click.Abort()


def get_workspace_id(workspace_id: Optional[str]) -> str:
    """
    Get workspace ID from argument or active workspace.
    Resolves names/slugs to UUIDs.
    
    Args:
        workspace_id: Optional workspace identifier (name, slug, or UUID)
        
    Returns:
        Workspace UUID
        
    Raises:
        click.Abort if no workspace specified or found
    """
    if workspace_id:
        return resolve_workspace_id(workspace_id)
    
    # Use active workspace
    active_id = config.get_workspace()
    if not active_id:
        click.echo("❌ No workspace specified and no active workspace set")
        click.echo("   Run 'mcpgw workspace set' or provide WORKSPACE_ID/NAME")
        raise click.Abort()
    
    return active_id


@click.group()
@click.option('--profile', envvar='MCPGW_PROFILE', help='Configuration profile to use')
@click.pass_context
def cli(ctx, profile: Optional[str]):
    """MCP Gateway CLI - Manage workspaces, backends, and agents"""
    # Store profile in context for use by subcommands if needed
    ctx.ensure_object(dict)
    ctx.obj['profile'] = profile


# ==================== CONFIG/PROFILE ====================

@cli.group()
def profile():
    """Profile management commands"""
    pass


@profile.command(name='list')
def list_profiles():
    """List all configuration profiles"""
    profiles = config.list_profiles()
    current = config.get_current_profile()
    
    if not profiles:
        click.echo("No profiles configured yet")
        click.echo("\nCreate one with: mcpgw profile create <name> --api-url <url>")
        return
    
    click.echo(f"\n📋 Configuration Profiles:\n")
    for p in profiles:
        marker = "→" if p == current else " "
        profile_data = config.get_profile_data(p)
        api_url = profile_data.get('api_url', 'Not set')
        
        click.echo(f"  {marker} {p}")
        click.echo(f"     API: {api_url}")
        if profile_data.get('token'):
            click.echo(f"     Auth: ✅ Logged in")
        else:
            click.echo(f"     Auth: ❌ Not logged in")
        click.echo()


@profile.command()
@click.argument('name')
@click.option('--api-url', required=True, help='API endpoint URL')
def create(name: str, api_url: str):
    """Create a new configuration profile"""
    config_data = config.load()
    if 'profiles' not in config_data:
        config_data['profiles'] = {}
    
    config_data['profiles'][name] = {'api_url': api_url}
    config.save(config_data)
    
    click.echo(f"✅ Created profile: {name}")
    click.echo(f"   API URL: {api_url}")
    click.echo(f"\nSwitch to it with: mcpgw profile use {name}")
    click.echo(f"Then login with: mcpgw auth login")


@profile.command()
@click.argument('name')
def use(name: str):
    """Switch to a different profile"""
    profiles = config.list_profiles()
    if name not in profiles:
        click.echo(f"❌ Profile '{name}' not found")
        click.echo(f"\nAvailable profiles: {', '.join(profiles) if profiles else 'none'}")
        click.echo(f"\nCreate it with: mcpgw profile create {name} --api-url <url>")
        raise click.Abort()
    
    config.switch_profile(name)
    profile_data = config.get_profile_data(name)
    api_url = profile_data.get('api_url', 'Not set')
    
    click.echo(f"✅ Switched to profile: {name}")
    click.echo(f"   API URL: {api_url}")
    
    if not profile_data.get('token'):
        click.echo(f"\n⚠️  Not logged in to this profile")
        click.echo(f"   Run: mcpgw auth login")


@profile.command()
def current():
    """Show current active profile"""
    current = config.get_current_profile()
    profile_data = config.get_profile_data(current)
    api_url = profile_data.get('api_url', config.get_api_url())
    
    click.echo(f"\n→ Current profile: {current}")
    click.echo(f"  API URL: {api_url}")
    
    if profile_data.get('token'):
        click.echo(f"  Auth: ✅ Logged in")
    else:
        click.echo(f"  Auth: ❌ Not logged in")


@profile.command()
@click.argument('name')
@click.confirmation_option(prompt='Delete this profile?')
def delete(name: str):
    """Delete a configuration profile"""
    if name == 'default':
        click.echo("❌ Cannot delete the default profile")
        raise click.Abort()
    
    current = config.get_current_profile()
    if name == current:
        click.echo("❌ Cannot delete the active profile")
        click.echo("   Switch to another profile first: mcpgw profile use <name>")
        raise click.Abort()
    
    config_data = config.load()
    if 'profiles' in config_data and name in config_data['profiles']:
        del config_data['profiles'][name]
        config.save(config_data)
        click.echo(f"✅ Deleted profile: {name}")
    else:
        click.echo(f"❌ Profile '{name}' not found")


# ==================== AUTH ====================

@cli.group()
def auth():
    """Authentication commands"""
    pass


@auth.command()
@click.option('--email', help='Your email address')
@click.option('--password', help='Your password')
@click.option('--token', help='JWT token from browser (localStorage.getItem("token"))')
@click.option('--browser/--no-browser', default=True, help='Open browser for login')
def login(email: Optional[str], password: Optional[str], token: Optional[str], browser: bool):
    """Login to MCP Gateway"""
    
    # Direct token input (quickest method)
    if token:
        config.set_token(token)
        try:
            headers = {'Authorization': f'Bearer {token}'}
            response = requests.get(f"{API_BASE}/me", headers=headers)
            user_data = response.json()
            user_email = user_data.get('user', {}).get('email', 'unknown')
            click.echo(f"✅ Logged in as {user_email}")
        except:
            click.echo("✅ Token saved")
        return
    
    # Browser-based OAuth flow (like gcloud)
    if browser and not (email and password):
        import webbrowser
        import http.server
        import socketserver
        import urllib.parse
        import socket
        
        # Determine UI URL - use profile API URL to derive UI URL, or use env var
        ui_url = os.getenv('MCPGW_UI_URL')
        if not ui_url:
            api_url = config.get_api_url()
            # Derive UI URL from API URL
            # http://localhost:8000/api/v1 → http://localhost:3000
            # https://api.mcpgw.io/api/v1 → https://mcpgw.io
            if 'localhost' in api_url:
                ui_url = 'http://localhost:3000'
            elif 'staging' in api_url:
                ui_url = 'https://staging.mcpgw.io'
            else:
                ui_url = 'https://mcpgw.io'
        
        # Find available port
        def find_free_port():
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.bind(('', 0))
                s.listen(1)
                port = s.getsockname()[1]
            return port
        
        PORT = find_free_port()
        received_token = {'token': None}
        
        class CallbackHandler(http.server.BaseHTTPRequestHandler):
            def do_GET(self):
                # Parse token from callback
                query = urllib.parse.urlparse(self.path).query
                params = urllib.parse.parse_qs(query)
                
                if 'token' in params:
                    received_token['token'] = params['token'][0]
                    self.send_response(200)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Access-Control-Allow-Origin', '*')
                    self.end_headers()
                    self.wfile.write(b"""
                        <html><body style="font-family: sans-serif; text-align: center; padding: 50px;">
                            <h1>&#x2705; Authentication Successful!</h1>
                            <p>You can close this window and return to the terminal.</p>
                            <script>setTimeout(() => window.close(), 2000);</script>
                        </body></html>
                    """)
                else:
                    self.send_response(400)
                    self.send_header('Content-type', 'text/html')
                    self.end_headers()
                    self.wfile.write(b"Missing token parameter")
            
            def log_message(self, format, *args):
                pass  # Suppress logs
        
        # Start server in background
        with socketserver.TCPServer(("", PORT), CallbackHandler) as httpd:
            click.echo("🌐 Opening browser for authentication...")
            click.echo(f"   Visit: {ui_url}/cli-auth?port={PORT}")
            click.echo("")
            
            # Open browser to UI
            auth_url = f"{ui_url}/cli-auth?port={PORT}"
            webbrowser.open(auth_url)
            
            click.echo("⏳ Waiting for authentication in browser...")
            click.echo("   (Login with your UI credentials)")
            click.echo("")
            
            # Wait for callback (timeout after 5 minutes)
            import time
            timeout = 300
            start = time.time()
            while received_token['token'] is None and (time.time() - start) < timeout:
                httpd.handle_request()
            
            if received_token['token']:
                config.set_token(received_token['token'])
                
                # Get user info
                try:
                    headers = {'Authorization': f'Bearer {received_token["token"]}'}
                    response = requests.get(f"{API_BASE}/me", headers=headers)
                    user_data = response.json()
                    user_email = user_data.get('user', {}).get('email', 'unknown')
                    click.echo(f"✅ Logged in as {user_email}")
                except:
                    click.echo("✅ Logged in successfully")
                
                return
            else:
                click.echo("❌ Authentication timed out", err=True)
                click.echo("   Try again or use: mcpgw auth login --no-browser")
                raise click.Abort()
    
    # Fallback to email/password flow
    if not email:
        email = click.prompt('Email')
    if not password:
        password = click.prompt('Password', hide_input=True)
    
    api_url = config.get_api_url()
    try:
        response = requests.post(
            f"{api_url}/login",
            json={'email': email, 'password': password}
        )
        response.raise_for_status()
        data = response.json()
        
        config.set_token(data['token'])
        click.echo(f"✅ Logged in as {email}")
        
    except requests.exceptions.RequestException as e:
        click.echo(f"❌ Login failed: {e}", err=True)
        raise click.Abort()


@auth.command()
def logout():
    """Logout from MCP Gateway"""
    config.set_token('')
    click.echo("✅ Logged out")


@auth.command()
def whoami():
    """Show current user info"""
    data = make_request('GET', '/me')
    user = data['user']
    click.echo(f"Email: {user['email']}")
    click.echo(f"Name: {user.get('name', 'N/A')}")
    click.echo(f"ID: {user['id']}")


# ==================== WORKSPACES ====================

@cli.group()
def workspace():
    """Workspace management"""
    pass


@workspace.command(name='list')
@click.option('--json-output', is_flag=True, help='Output as JSON')
def list_workspaces(json_output: bool):
    """List all workspaces"""
    data = make_request('GET', '/workspaces')
    
    if json_output:
        click.echo(json.dumps(data['workspaces'], indent=2))
        return
    
    workspaces = data['workspaces']
    if not workspaces:
        click.echo("No workspaces found")
        return
    
    click.echo(f"\n📁 Found {len(workspaces)} workspace(s):\n")
    for ws in workspaces:
        click.echo(f"  {ws['name']}")
        click.echo(f"    ID: {ws['id']}")
        if 'role' in ws:
            click.echo(f"    Role: {ws['role']}")
        if 'plan_tier' in ws:
            click.echo(f"    Plan: {ws['plan_tier']}")
        if 'backend_count' in ws:
            click.echo(f"    Backends: {ws['backend_count']}")
        click.echo()


@workspace.command()
@click.argument('workspace_identifier')
def get(workspace_identifier: str):
    """Get workspace details (by name or UUID)"""
    workspace_id = resolve_workspace_id(workspace_identifier)
    data = make_request('GET', f'/workspaces/{workspace_id}')
    
    ws = data['workspace']
    click.echo(f"\n📁 {ws['name']}")
    click.echo(f"ID: {ws['id']}")
    click.echo(f"Created: {ws['created_at']}")
    click.echo(f"Proxy URL: {ws.get('mcp_proxy_url', 'N/A')}")
    
    click.echo(f"\n👥 Members ({len(data['members'])}):")
    for member in data['members']:
        click.echo(f"  • {member['email']} ({member['role']})")
    
    click.echo(f"\n🔌 Backends ({len(data['backends'])}):")
    for backend in data['backends']:
        click.echo(f"  • {backend['name']} - {backend['url']}")


@workspace.command()
@click.option('--name', prompt=True, help='Workspace name')
@click.option('--slug', help='URL slug (auto-generated if not provided)')
def create(name: str, slug: Optional[str]):
    """Create a new workspace"""
    payload = {'name': name}
    if slug:
        payload['slug'] = slug
    
    data = make_request('POST', '/workspaces', data=payload)
    ws = data['workspace']
    
    click.echo(f"✅ Created workspace: {ws['name']}")
    click.echo(f"   ID: {ws['id']}")
    click.echo(f"   URL: {ws.get('mcp_proxy_url', 'N/A')}")


@workspace.command()
@click.argument('workspace_identifier')
@click.confirmation_option(prompt='Are you sure you want to delete this workspace?')
def delete(workspace_identifier: str):
    """Delete a workspace (by name or UUID)"""
    workspace_id = resolve_workspace_id(workspace_identifier)
    make_request('DELETE', f'/workspaces/{workspace_id}')
    click.echo(f"✅ Deleted workspace {workspace_id}")


@workspace.command()
@click.argument('workspace_identifier', required=False)
def set(workspace_identifier: Optional[str]):
    """Set the active workspace by name or UUID (or select from list)"""
    if not workspace_identifier:
        # Show list and let user select
        data = make_request('GET', '/workspaces')
        workspaces = data['workspaces']
        
        if not workspaces:
            click.echo("❌ No workspaces found")
            return
        
        click.echo("\n📁 Available workspaces:\n")
        for idx, ws in enumerate(workspaces, 1):
            click.echo(f"  {idx}. {ws['name']}")
            click.echo(f"     ID: {ws['id']}")
        
        choice = click.prompt('\nSelect workspace number', type=int)
        if choice < 1 or choice > len(workspaces):
            click.echo("❌ Invalid selection")
            return
        
        workspace_id = workspaces[choice - 1]['id']
        workspace_name = workspaces[choice - 1]['name']
    else:
        # Resolve name/slug/UUID to workspace ID
        workspace_id = resolve_workspace_id(workspace_identifier)
        data = make_request('GET', f'/workspaces/{workspace_id}')
        workspace_name = data['workspace']['name']
    
    config.set_workspace(workspace_id)
    click.echo(f"✅ Active workspace set to: {workspace_name}")
    click.echo(f"   ID: {workspace_id}")


@workspace.command()
def current():
    """Show the current active workspace"""
    workspace_id = config.get_workspace()
    
    if not workspace_id:
        click.echo("❌ No active workspace set")
        click.echo("   Run 'mcpgw workspace set' to select one")
        return
    
    try:
        data = make_request('GET', f'/workspaces/{workspace_id}')
        ws = data['workspace']
        click.echo(f"\n📁 Current workspace: {ws['name']}")
        click.echo(f"   ID: {ws['id']}")
        click.echo(f"   Created: {ws['created_at']}")
    except:
        click.echo(f"❌ Active workspace {workspace_id} not found")
        click.echo("   Run 'mcpgw workspace set' to select a new one")


@workspace.command()
def unset():
    """Clear the active workspace"""
    config.clear_workspace()
    click.echo("✅ Active workspace cleared")


# ==================== BACKENDS ====================

@cli.group()
def backend():
    """Backend management"""
    pass


@backend.command(name='list')
@click.argument('workspace_identifier', required=False)
def list_backends(workspace_identifier: Optional[str]):
    """List backends in a workspace (by name/UUID, or uses active workspace)"""
    workspace_id = get_workspace_id(workspace_identifier)
    
    data = make_request('GET', f'/workspaces/{workspace_id}/backends')
    
    backends = data['backends']
    if not backends:
        click.echo("No backends configured")
        return
    
    click.echo(f"\n🔌 {len(backends)} backend(s):\n")
    for b in backends:
        auth_status = "✅" if b.get('authenticated') else "❌"
        click.echo(f"  {auth_status} {b['name']}")
        click.echo(f"     ID: {b['id']}")
        click.echo(f"     URL: {b['url']}")
        click.echo(f"     Auth: {b.get('auth_mode', 'none')}")
        click.echo()


@backend.command()
@click.argument('workspace_identifier', required=False)
@click.option('--name', prompt=True)
@click.option('--url', prompt=True)
@click.option('--auth-mode', default='none', type=click.Choice(['none', 'oauth', 'api_key']))
def add(workspace_identifier: Optional[str], name: str, url: str, auth_mode: str):
    """Add backend to workspace (by name/UUID, or uses active workspace)"""
    workspace_id = get_workspace_id(workspace_identifier)
    
    data = make_request('POST', f'/workspaces/{workspace_id}/backends', data={
        'name': name,
        'url': url,
        'auth_mode': auth_mode
    })
    click.echo(f"✅ Added backend: {name}")


@backend.command()
@click.argument('backend_id')
@click.argument('workspace_identifier', required=False)
@click.confirmation_option(prompt='Remove this backend?')
def remove(backend_id: str, workspace_identifier: Optional[str]):
    """Remove backend from workspace (by name/UUID, or uses active workspace)"""
    workspace_id = get_workspace_id(workspace_identifier)
    
    make_request('DELETE', f'/workspaces/{workspace_id}/backends/{backend_id}')
    click.echo(f"✅ Removed backend {backend_id}")


# ==================== CATALOG ====================

@cli.group()
def catalog():
    """Backend catalog"""
    pass


@catalog.command(name='list')
@click.option('--category', help='Filter by category')
def list_catalog(category: Optional[str]):
    """List available backends from catalog"""
    params = {'category': category} if category else None
    data = make_request('GET', '/backend-catalog', params=params)
    
    backends = data.get('catalog', [])
    click.echo(f"\n📦 {len(backends)} backend(s) available:\n")
    
    for b in backends:
        click.echo(f"  {b['name']} ({b['category']})")
        click.echo(f"    ID: {b['id']}")
        click.echo(f"    {b.get('description', 'No description')}")
        click.echo()


@catalog.command()
@click.argument('backend_id')
@click.argument('workspace_identifier', required=False)
def enable(backend_id: str, workspace_identifier: Optional[str]):
    """Enable a catalog backend in workspace (by name/UUID, or uses active workspace)"""
    workspace_id = get_workspace_id(workspace_identifier)
    
    data = make_request('POST', f'/workspaces/{workspace_id}/backends/enable', data={
        'backend_catalog_id': backend_id
    })
    click.echo(f"✅ Enabled backend in workspace")


# ==================== AGENTS ====================

@cli.group()
def agent():
    """Agent management"""
    pass


@agent.command(name='list')
@click.argument('workspace_identifier', required=False)
def list_agents(workspace_identifier: Optional[str]):
    """List agents in workspace (by name/UUID, or uses active workspace)"""
    workspace_id = get_workspace_id(workspace_identifier)
    
    data = make_request('GET', f'/{workspace_id}/agents')
    
    agents = data.get('agents', [])
    if not agents:
        click.echo("No agents found")
        return
    
    click.echo(f"\n🤖 {len(agents)} agent(s):\n")
    for a in agents:
        status_icon = "🟢" if a.get('status') == 'active' else "🔴"
        click.echo(f"  {status_icon} {a['name']}")
        click.echo(f"     Key: {a['key_prefix']}...")
        click.echo(f"     Created: {a['created_at']}")
        click.echo(f"     Last used: {a.get('last_used_at', 'Never')}")
        click.echo()


@agent.command()
@click.argument('workspace_identifier', required=False)
@click.option('--name', prompt=True, help='Agent name')
def create(workspace_identifier: Optional[str], name: str):
    """Create a new agent (by name/UUID, or uses active workspace)"""
    workspace_id = get_workspace_id(workspace_identifier)
    
    data = make_request('POST', f'/{workspace_id}/agents', data={'name': name})
    
    click.echo(f"\n✅ Created agent: {data['agent']['name']}")
    click.echo(f"\n⚠️  SAVE THIS API KEY - it won't be shown again:")
    click.echo(f"\n    {data['api_key']}\n")


if __name__ == '__main__':
    cli()
