# 🚀 AI Gateway CLI

**Enterprise-grade command-line interface for managing Cequence AI Gateway Private Cloud deployments.**

Complete lifecycle management with comprehensive monitoring, security, and automation capabilities.

[![License](https://img.shields.io/badge/License-Proprietary-blue.svg)](LICENSE)
[![Go Version](https://img.shields.io/badge/Go-1.24+-00ADD8.svg)](https://golang.org/)
[![Kubernetes](https://img.shields.io/badge/Kubernetes-v1.28+-326CE5.svg)](https://kubernetes.io/)

## ✨ Key Features

- 🚀 **Smart Deployment**: Pre-flight validation, automatic credential injection, cluster-agnostic compatibility
- 🔍 **Comprehensive Monitoring**: Real-time health checks, log aggregation, event monitoring, intelligent alerting
- 🔐 **Enterprise Security**: RBAC validation, auto-generated permissions, secure credential storage
- 🛠️ **Developer Experience**: User-friendly errors, JSON output, extensive filtering, automation-ready
- 📦 **Production Ready**: Latest Kubernetes APIs, cross-platform binaries, minimal cluster impact

## 📦 Installation

### Quick Install (Unix/Linux/macOS)
```bash
curl -sSL https://gitlab.com/cequence/ai-gateway/cli/-/raw/main/install.sh | sh
```

### Install Specific Version
```bash
curl -sSL https://gitlab.com/cequence/ai-gateway/cli/-/raw/main/install.sh | sh -s v1.0.0
```

### From Source
```bash
git clone https://gitlab.com/cequence/ai-gateway/cli.git
cd cli/src
go build -o aigateway .
```

### Download Binaries
Download pre-built binaries from the [releases page](https://gitlab.com/cequence/ai-gateway/cli/-/releases).

## 🚀 Quick Start

```bash
# 1. Initialize CLI with your tenant
aigateway init --tenant my-company

# 2. Authenticate using OAuth device flow
aigateway login

# 3. Check RBAC permissions
aigateway permissions

# 4. Deploy AI Gateway
aigateway deploy install --wait

# 5. Monitor deployment health
aigateway status
```

## 📋 Command Reference

### **🔧 Configuration & Authentication**
```bash
aigateway init --tenant <tenant>          # Initialize CLI configuration
aigateway config                          # Display current configuration
aigateway login                           # OAuth device flow authentication
aigateway logout                          # Clear authentication
```

### **🔐 Security & Permissions**
```bash
aigateway permissions                     # Check RBAC permissions
aigateway permissions --generate-role     # Generate Role manifest
aigateway permissions --json              # JSON output for automation
```

### **🚀 Deployment Operations**
```bash
# Installation & Management
aigateway deploy install                  # Install AI Gateway
aigateway deploy install --replicas 5    # Custom deployment options
aigateway deploy upgrade                  # Upgrade existing deployment
aigateway deploy uninstall               # Remove AI Gateway

# Validation & Export
aigateway deploy describe                 # Show bundled manifests
aigateway deploy export -o ./manifests   # Export processed manifests

# Control Options
--validate                               # Dry-run validation (default)
--skip-permission-checks                 # Skip RBAC validation
--wait                                   # Wait for deployment readiness
--replicas 3                            # Replica count
--service-type LoadBalancer             # Service configuration
--storage-class fast-ssd                # Storage options
```

### **📊 Monitoring & Health**
```bash
# Status Monitoring
aigateway status                         # Overall health status
aigateway status --watch                 # Continuous monitoring
aigateway status --verbose               # Detailed pod information
aigateway status --json                  # JSON output

# Log Management
aigateway logs                           # All component logs
aigateway logs aigateway-api-0          # Specific pod logs
aigateway logs --follow --errors        # Real-time error stream
aigateway logs --since 1h               # Time-based filtering
aigateway logs --keywords "database"    # Keyword filtering

# Event Monitoring
aigateway events                         # Recent Kubernetes events
aigateway events --critical             # Critical events only
aigateway events --watch                # Real-time event stream

# Real-time Dashboard
aigateway monitor                        # Comprehensive monitoring
aigateway monitor --interval 10s        # Custom monitoring interval
aigateway monitor --quiet               # Alerts only mode
```

### **🔧 Cluster Operations**
```bash
aigateway cluster info                   # Cluster information
aigateway api config                     # API configuration
aigateway version                        # Version information
```

## 🎯 Monitoring Capabilities

### **Component Health Tracking**
- ✅ **Deployments**: Replica status, rollout progress
- ✅ **StatefulSets**: Pod readiness, storage health
- ✅ **Services**: Endpoint status, load balancer provisioning
- ✅ **ConfigMaps/Secrets**: Configuration integrity
- ✅ **PVCs**: Storage binding and capacity
- ✅ **Pods**: Container health, restart counts, events

### **Real-time Alerting**
```bash
🚨 ALERT: StatefulSet/aigateway-db is unhealthy: 1/3 replicas ready
🔥 ERROR LOG [aigateway-api-0/gateway]: Database connection timeout
⚠️  CRITICAL EVENT: BackOff - Back-off restarting failed container

💡 RECOMMENDATIONS:
   • Run 'aigateway logs --errors --since 5m' to see recent errors
   • Run 'aigateway events --critical --since 10m' to see critical events
```

### **Intelligent Issue Detection**
- 🔍 **New Issue Detection**: Automatically identifies emerging problems
- 🔄 **Resolution Tracking**: Monitors issue resolution
- 📈 **Pattern Recognition**: Identifies recurring issues
- 💡 **Smart Recommendations**: Contextual troubleshooting guidance

## 🛡️ Security Features

### **RBAC Management**
- **Permission Validation**: Comprehensive RBAC checking before deployment
- **Auto-generated Roles**: Creates minimal required permissions
- **Cross-cluster Compatibility**: Works with any Kubernetes RBAC setup

### **Secure Authentication**
- **OAuth 2.0 Device Flow**: Industry-standard authentication
- **Cross-platform Keyring**: Secure credential storage
- **Automatic Token Refresh**: Seamless session management

## 📈 Production Examples

### **CI/CD Pipeline Integration**
```bash
#!/bin/bash
# Generate and apply RBAC
aigateway permissions --generate-role | kubectl apply -f -

# Deploy with validation
aigateway deploy upgrade --wait

# Verify health
aigateway status --json | jq -e '.summary.Unhealthy == 0'
```

### **Monitoring Setup**
```bash
# Long-running production monitor
aigateway monitor --interval 60s --log-level ERROR &

# Error log collection
aigateway logs --follow --errors | tee /var/log/aigateway-errors.log &

# Critical event monitoring
aigateway events --watch --critical
```

### **Troubleshooting Workflow**
```bash
# 1. Quick health assessment
aigateway status --verbose

# 2. Error investigation
aigateway logs --errors --since 30m
aigateway events --critical --since 1h

# 3. Real-time monitoring during incident
aigateway monitor --interval 10s --quiet
```

## 🔧 Advanced Configuration

### **Config File Locations**
- **Windows**: `%APPDATA%\cequence-aigateway\config.json`
- **macOS**: `~/Library/Application Support/cequence-aigateway/config.json`
- **Linux**: `~/.config/cequence-aigateway/config.json`

### **Authentication Storage**
- **Primary**: System keyring (Keychain/GNOME/Windows Credential Manager)
- **Fallback**: Encrypted file storage with 0600 permissions

### **JSON Output for Automation**
```bash
# Health metrics
aigateway status --json | jq '.summary'

# Error analysis
aigateway logs --errors --json | jq '.logs[] | select(.level == "ERROR")'

# Event data
aigateway events --critical --json | jq '.events[].reason'
```

## 🏗️ Building from Source

### **Requirements**
- Go 1.24+
- Make (optional)

### **Build Commands**
```bash
# Development build
go build -o aigateway .

# Production build with optimizations
make build

# Cross-platform builds
make snapshot

# Run tests
make test

# Clean artifacts
make clean
```

### **Build Features**
- **Manifest Bundling**: Kubernetes manifests embedded at build time
- **Cross-platform**: Builds for Linux, macOS, Windows (AMD64/ARM64)
- **Version Injection**: Git commit, build date, and version info
- **Optimized Binaries**: Minimal size with full functionality

## 📚 Documentation

- **[Monitoring Guide](examples/monitoring-guide.md)**: Comprehensive monitoring documentation
- **[RBAC Setup](examples/rbac-setup.md)**: Permission configuration guide
- **[API Reference](docs/api.md)**: Complete API documentation
- **[Troubleshooting](docs/troubleshooting.md)**: Common issues and solutions

## 🚀 CI/CD Integration

The AI Gateway CLI is designed for seamless integration with CI/CD pipelines using OAuth 2.0 client credentials flow while maintaining all interactive features for development.

**Key Benefits:**
- **Environment-First Design**: All CI/CD configuration via `AIGATEWAY_*` environment variables
- **Automatic Mode Detection**: No flags needed - automatically detects CI/CD vs interactive mode
- **Standard OAuth Defaults**: Uses standard OAuth endpoints (`https://auth.aigateway.cequence.ai/oauth2/v1/token`)
- **Dual Authentication**: OAuth device flow (interactive) or client credentials (CI/CD)
- **Zero Breaking Changes**: Existing interactive workflows remain unchanged

### **Authentication for CI/CD**

#### **1. Interactive Mode (Development)**
```bash
# Standard OAuth device flow
aigateway login
aigateway deploy install
```

#### **2. CI/CD Mode (Automated)**
```bash
# Required environment variables for automated deployment
export AIGATEWAY_TENANT="my-company"
export AIGATEWAY_CLIENT_ID="your-client-id"
export AIGATEWAY_CLIENT_SECRET="your-client-secret"
export AIGATEWAY_CI_MODE="true"

# Optional customization
export AIGATEWAY_NAMESPACE="production"

# CLI automatically detects CI mode and uses structured output
aigateway deploy install --wait
aigateway status
```

### **Environment Variables**

| Variable | Description | Required |
|----------|-------------|----------|
| `AIGATEWAY_TENANT` | Tenant identifier | ✅ |
| `AIGATEWAY_CLIENT_ID` | OAuth client ID | ✅ (CI/CD mode only) |
| `AIGATEWAY_CLIENT_SECRET` | OAuth client secret for CI/CD | ✅ (CI/CD mode) |
| `AIGATEWAY_CI_MODE` | Enable CI/CD mode | ✅ (CI/CD mode) |
| `AIGATEWAY_NAMESPACE` | Kubernetes namespace | ❌ (default: aigateway) |
| `AIGATEWAY_AUTH_URL` | Authentication URL | ❌ (default: provided) |
| `AIGATEWAY_API_URL` | API endpoint URL | ❌ (default: provided) |
| `AIGATEWAY_OAUTH_TOKEN_URL` | OAuth token endpoint | ❌ (default: standard endpoint) |
| `AIGATEWAY_OAUTH_DEVICE_URL` | OAuth device endpoint | ❌ (default: standard endpoint) |
| `AIGATEWAY_OAUTH_SCOPE` | OAuth scope | ❌ (default: openid profile email) |

### **Automatic Mode Detection**

The CLI automatically detects the environment and adjusts behavior:

```bash
# Interactive Mode (when AIGATEWAY_CI_MODE is not set)
# - Colorful output with emojis
# - Interactive prompts
# - OAuth device flow authentication
# - Uses fixed client ID for device authorization

# CI/CD Mode (when AIGATEWAY_CI_MODE=true)
# - Structured JSON output
# - Non-interactive behavior
# - Client credentials authentication
# - Requires custom client ID via AIGATEWAY_CLIENT_ID
```

**Note**: `AIGATEWAY_CLIENT_ID` is only required for CI/CD mode. Interactive mode uses a fixed client ID for device authorization flow.

### **GitLab CI/CD Example**

```yaml
# .gitlab-ci.yml
deploy_production:
  stage: deploy
  image: alpine:latest
  variables:
    AIGATEWAY_TENANT: "my-company"
    AIGATEWAY_CLIENT_ID: "your-client-id"
    AIGATEWAY_NAMESPACE: "production"
    AIGATEWAY_CI_MODE: "true"
    # CLIENT_SECRET should be set in GitLab CI/CD Variables (masked)
    AIGATEWAY_CLIENT_SECRET: $AIGATEWAY_CLIENT_SECRET
  before_script:
    - wget -O /usr/local/bin/aigateway https://releases.cequence.ai/aigateway/latest/aigateway-linux-amd64
    - chmod +x /usr/local/bin/aigateway
  script:
    - aigateway deploy install --wait
    - aigateway status --json > deployment-status.json
  artifacts:
    reports:
      junit: deployment-status.json
    expire_in: 1 week
  only:
    - main
```

### **GitHub Actions Example**

```yaml
# .github/workflows/deploy.yml
name: Deploy AI Gateway
on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Download AI Gateway CLI
        run: |
          curl -sSL https://releases.cequence.ai/install.sh | sh
          sudo mv aigateway /usr/local/bin/

      - name: Deploy to Production
        env:
          AIGATEWAY_TENANT: my-company
          AIGATEWAY_CLIENT_ID: ${{ secrets.AIGATEWAY_CLIENT_ID }}
          AIGATEWAY_CLIENT_SECRET: ${{ secrets.AIGATEWAY_CLIENT_SECRET }}
          AIGATEWAY_NAMESPACE: production
          AIGATEWAY_CI_MODE: true
        run: |
          aigateway deploy install --wait
          aigateway status --json
```

### **Azure DevOps Example**

```yaml
# azure-pipelines.yml
trigger:
- main

pool:
  vmImage: 'ubuntu-latest'

variables:
  AIGATEWAY_TENANT: 'my-company'
  AIGATEWAY_CLIENT_ID: 'your-client-id'
  AIGATEWAY_NAMESPACE: 'production'
  AIGATEWAY_CI_MODE: 'true'

steps:
- script: |
    curl -sSL https://releases.cequence.ai/install.sh | sh
    sudo mv aigateway /usr/local/bin/
  displayName: 'Install AI Gateway CLI'

- script: |
    aigateway deploy install --wait
    aigateway status --json > $(Agent.TempDirectory)/status.json
  env:
    AIGATEWAY_CLIENT_ID: $(client-id)
    AIGATEWAY_CLIENT_SECRET: $(client-secret)
  displayName: 'Deploy AI Gateway'

- publishTestResults:
    testResultsFiles: '$(Agent.TempDirectory)/status.json'
    testRunTitle: 'AI Gateway Deployment Status'
```

### **Advanced CI/CD Features**

#### **Environment-Based Configuration**
```bash
# Required CI/CD configuration
export AIGATEWAY_TENANT="my-company"
export AIGATEWAY_CLIENT_ID="your-client-id"
export AIGATEWAY_CLIENT_SECRET="your-client-secret"
export AIGATEWAY_CI_MODE="true"

# Optional customization
export AIGATEWAY_NAMESPACE="production"

# Deploy (automatically uses CI mode with standard OAuth endpoints)
aigateway deploy install --wait
```

#### **Structured JSON Output**
```bash
# In CI mode (AIGATEWAY_CI_MODE=true), all output is automatically JSON structured

# Health check with JSON output
aigateway status --json | jq '.summary.Unhealthy'

# Error detection
aigateway logs --errors --json --since 5m | jq '.logs[] | select(.level == "ERROR")'

# Event monitoring
aigateway events --critical --json | jq '.events[].reason'
```

#### **Pipeline Health Checks**
```bash
#!/bin/bash
# health-check.sh

# Deploy with health verification
aigateway deploy install --wait

# Verify deployment success
STATUS=$(aigateway status --json | jq -r '.summary.Unhealthy // 0')
if [ "$STATUS" -gt 0 ]; then
    echo "❌ AI Gateway has $STATUS unhealthy components"
    aigateway logs --errors --since 5m --json
    exit 1
fi

echo "✅ AI Gateway deployment successful"
aigateway status --json
```

### **Security Best Practices**

#### **1. Client Secret Management**
- Store `AIGATEWAY_CLIENT_SECRET` in your CI/CD secret management system
- Never commit client secrets to version control
- Use separate client credentials for different environments

#### **2. Least Privilege Access**
```bash
# Generate RBAC role for CI/CD
aigateway permissions --generate-role > ci-rbac.yaml
kubectl apply -f ci-rbac.yaml
```

#### **3. Environment Isolation**
```bash
# Different namespaces per environment
export AIGATEWAY_NAMESPACE="staging"    # Staging
export AIGATEWAY_NAMESPACE="production" # Production
```

### **Monitoring in CI/CD**

#### **Deployment Verification**
```bash
# Wait for readiness and verify
aigateway deploy install --wait
aigateway monitor --interval 30s --quiet --timeout 5m
```

#### **Automated Alerts**
```bash
# Check for critical issues
ERRORS=$(aigateway logs --errors --json --since 5m | jq '.count // 0')
if [ "$ERRORS" -gt 5 ]; then
    curl -X POST "$SLACK_WEBHOOK" -d '{"text":"🚨 AI Gateway errors detected"}'
fi
```

## 🤝 Support

- **Issues**: [GitLab Issues](https://gitlab.com/cequence/ai-gateway/cli/-/issues)
- **Documentation**: [Wiki](https://gitlab.com/cequence/ai-gateway/cli/-/wikis/home)
- **Enterprise Support**: Contact your Cequence representative

## 📊 Compatibility

- **Kubernetes**: v1.28+ (tested with v1.34)
- **Platforms**: Linux, macOS, Windows
- **Architectures**: AMD64, ARM64
- **Clusters**: EKS, GKE, AKS, on-premises, managed Kubernetes

## 📄 License

Copyright © 2025 Cequence Security. All rights reserved.

---

**🎯 The AI Gateway CLI provides complete lifecycle management for AI Gateway deployments with enterprise-grade monitoring, security, and automation capabilities.**