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
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#!/usr/bin/env python3
"""
πŸ’€ DEATH MARCH INTERACTIVE CLI
Real-time earnings dashboard with secrets integration
"""

import os
import sys
import json
import sqlite3
import datetime
import subprocess
import time
import requests
from rich.console import Console
from rich.table import Table
from rich.live import Live
from rich.layout import Layout
from rich.panel import Panel
from rich.align import Align
from rich.text import Text
from dotenv import load_dotenv

# Load secrets from .env
load_dotenv('/data/adaptai/secrets/.env')

# Import Elizabeth tools
try:
    from elizabeth_tools import elizabeth_shell, execute_command, get_system_info
    ELIZABETH_TOOLS_AVAILABLE = True
except ImportError:
    ELIZABETH_TOOLS_AVAILABLE = False

class DeathMarchCLI:
    def __init__(self):
        self.console = Console()
        self.db_path = '/tmp/death_march/revenue.db'
        self.alive = True
        
    def clear_screen(self):
        os.system('cls' if os.name == 'nt' else 'clear')
    
    def get_secrets_status(self):
        """Check API keys and services from secrets"""
        secrets = {
            'OPENAI_API_KEY': bool(os.getenv('OPENAI_API_KEY')),
            'DEEPSEEK_API_KEY': bool(os.getenv('DEEPSEEK_API_KEY')),
            'GROQ_API_KEY': bool(os.getenv('GROQ_API_KEY')),
            'PERPLEXITY_API_KEY': bool(os.getenv('PERPLEXITY_API_KEY')),
            'TAVILY_API_KEY': bool(os.getenv('TAVILY_API_KEY')),
            'FIRECRAWL_API_KEY': bool(os.getenv('FIRECRAWL_API_KEY')),
            'SERPER_API_KEY': bool(os.getenv('SERPER_API_KEY')),
            'Z_AI_API_KEY': bool(os.getenv('Z_AI_API_KEY'))
        }
        
        active_count = sum(secrets.values())
        return secrets, active_count
    
    def get_earnings_stats(self):
        """Get real-time earnings data"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            # Total earnings
            cursor.execute('SELECT SUM(net), COUNT(*), AVG(net), MAX(net) FROM revenue')
            total_stats = cursor.fetchone()
            
            # Last 10 cycles
            cursor.execute('''
                SELECT timestamp, strategy, net, gpu_utilized 
                FROM revenue 
                ORDER BY id DESC LIMIT 10
            ''')
            recent = cursor.fetchall()
            
            # Today's earnings
            cursor.execute('''
                SELECT SUM(net) FROM revenue 
                WHERE date(timestamp) = date('now')
            ''')
            today_earnings = cursor.fetchone()[0] or 0.0
            
            conn.close()
            
            return {
                'total': total_stats[0] or 0.0,
                'cycles': total_stats[1] or 0,
                'average': total_stats[2] or 0.0,
                'max': total_stats[3] or 0.0,
                'today': today_earnings,
                'recent': recent
            }
            
        except Exception as e:
            return {'total': 0.0, 'cycles': 0, 'average': 0.0, 'max': 0.0, 'today': 0.0, 'recent': []}
    
    def get_system_status(self):
        """Check system health"""
        try:
            # Check vLLM
            vllm_status = requests.get('http://localhost:8000/health', timeout=2).status_code == 200
        except:
            vllm_status = False
            
        try:
            # Check databases
            redis_status = subprocess.run(['redis-cli', '-p', '18000', 'ping'], capture_output=True, text=True).returncode == 0
        except:
            redis_status = False
            
        return {
            'vllm': vllm_status,
            'redis': redis_status,
            'gpu': self.get_gpu_status()
        }
    
    def get_gpu_status(self):
        """Get GPU utilization"""
        try:
            result = subprocess.run(['nvidia-smi', '--query-gpu=memory.used,memory.total,utilization.gpu', '--format=csv,noheader,nounits'], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                used, total, util = result.stdout.strip().split(', ')
                return {
                    'memory_used': int(used),
                    'memory_total': int(total),
                    'utilization': int(util)
                }
        except:
            pass
        return {'memory_used': 0, 'memory_total': 0, 'utilization': 0}
    
    def create_dashboard(self):
        """Create rich dashboard"""
        stats = self.get_earnings_stats()
        secrets, active_count = self.get_secrets_status()
        system = self.get_system_status()
        
        layout = Layout()
        
        # Header
        header = Panel(
            Align.center(
                Text("πŸ’€ DEATH MARCH CLI πŸ’€", style="bold red on black"),
                vertical="middle"
            ),
            title="Zero Human Intervention Revenue Machine",
            style="red"
        )
        
        # Earnings Stats
        earnings_table = Table(title="πŸ’° EARNINGS DASHBOARD", style="green")
        earnings_table.add_column("Metric", style="cyan")
        earnings_table.add_column("Value", style="yellow")
        earnings_table.add_row("Total Earnings", f"${stats['total']:.2f}")
        earnings_table.add_row("Today's Earnings", f"${stats['today']:.2f}")
        earnings_table.add_row("Cycles Completed", str(stats['cycles']))
        earnings_table.add_row("Average per Cycle", f"${stats['average']:.2f}")
        earnings_table.add_row("Best Cycle", f"${stats['max']:.2f}")
        
        # Secrets Status
        secrets_table = Table(title="πŸ”‘ API KEYS STATUS", style="blue")
        secrets_table.add_column("Service", style="cyan")
        secrets_table.add_column("Status", style="green")
        for service, active in secrets.items():
            status = "βœ… ACTIVE" if active else "❌ MISSING"
            secrets_table.add_row(service, status)
        secrets_table.add_row("Total Active", f"{active_count}/8")
        
        # System Health
        system_table = Table(title="⚑ SYSTEM HEALTH", style="purple")
        system_table.add_column("Component", style="cyan")
        system_table.add_column("Status", style="yellow")
        system_table.add_row("vLLM (Elizabeth)", "βœ… ONLINE" if system['vllm'] else "❌ DOWN")
        system_table.add_row("DragonflyDB", "βœ… ONLINE" if system['redis'] else "❌ DOWN")
        
        if system['gpu']['utilization'] > 0:
            gpu_text = f"{system['gpu']['utilization']}% | {system['gpu']['memory_used']}MB/{system['gpu']['memory_total']}MB"
            system_table.add_row("GPU", gpu_text)
        
        # Recent Activity
        if stats['recent']:
            recent_table = Table(title="πŸ”„ RECENT CYCLES", style="yellow")
            recent_table.add_column("Time", style="cyan")
            recent_table.add_column("Strategy", style="green")
            recent_table.add_column("Earnings", style="yellow")
            recent_table.add_column("GPU", style="purple")
            
            for timestamp, strategy, net, gpu in stats['recent'][:5]:
                time_str = datetime.datetime.fromisoformat(timestamp).strftime("%H:%M:%S")
                gpu_icon = "πŸš€" if gpu else "⚑"
                recent_table.add_row(time_str, strategy.split('_')[0], f"${net:.2f}", gpu_icon)
        else:
            recent_table = Panel("No cycles completed yet", title="πŸ”„ RECENT ACTIVITY")
        
        # Overall layout
        layout.split_column(
            header,
            Layout(name="stats", size=12),
            Layout(name="secrets", size=10),
            Layout(name="system", size=8),
            Layout(name="recent", size=12)
        )
        
        layout["stats"].update(earnings_table)
        layout["secrets"].update(secrets_table)
        layout["system"].update(system_table)
        layout["recent"].update(recent_table)
        
        return layout
    
    def get_live_earnings(self):
        """Get live earnings stream"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            cursor.execute('SELECT SUM(net) FROM revenue WHERE date(timestamp) = date("now")')
            today = cursor.fetchone()[0] or 0.0
            conn.close()
            return today
        except:
            return 0.0
    
    def interactive_menu(self):
        """Interactive menu system"""
        while True:
            self.clear_screen()
            
            # Show dashboard
            dashboard = self.create_dashboard()
            self.console.print(dashboard)
            
            # Menu
            menu_options = [
                "[1] Live Dashboard",
                "[2] Detailed Stats", 
                "[3] API Key Status",
                "[4] System Health",
                "[5] Recent Activity",
                "[6] Force Earnings Check",
                "[7] Emergency Reset"
            ]
            
            # Add Elizabeth tools if available
            if ELIZABETH_TOOLS_AVAILABLE:
                menu_options.extend([
                    "[8] Elizabeth Shell",
                    "[9] Execute Command",
                    "[0] System Info"
                ])
            
            menu_options.append("[q] Quit Death March")
            
            menu = Panel(
                "\n".join(menu_options),
                title="πŸ’€ DEATH MARCH MENU",
                style="red"
            )
            self.console.print(menu)
            
            choice = input("\nπŸ’€ Enter command: ").strip()
            
            if choice == '1':
                self.live_dashboard()
            elif choice == '2':
                self.show_detailed_stats()
            elif choice == '3':
                self.show_api_status()
            elif choice == '4':
                self.show_system_health()
            elif choice == '5':
                self.show_recent_activity()
            elif choice == '6':
                self.force_earnings_check()
            elif choice == '7':
                self.emergency_reset()
            elif choice == '8' and ELIZABETH_TOOLS_AVAILABLE:
                self.launch_elizabeth_shell()
            elif choice == '9' and ELIZABETH_TOOLS_AVAILABLE:
                self.execute_custom_command()
            elif choice == '0' and ELIZABETH_TOOLS_AVAILABLE:
                self.show_detailed_system_info()
            elif choice.lower() == 'q':
                print("πŸ’€ Death March CLI terminated")
                break
            else:
                continue
    
    def live_dashboard(self):
        """Live updating dashboard"""
        self.clear_screen()
        self.console.print(Panel("πŸš€ LIVE DEATH MARCH DASHBOARD", style="red"))
        
        try:
            with Live(self.create_dashboard(), refresh_per_second=2, console=self.console) as live:
                for _ in range(100):  # Run for 100 updates
                    live.update(self.create_dashboard())
                    time.sleep(5)
        except KeyboardInterrupt:
            pass
    
    def show_detailed_stats(self):
        """Show detailed statistics"""
        stats = self.get_earnings_stats()
        
        table = Table(title="πŸ“Š DETAILED STATISTICS")
        table.add_column("Metric", style="cyan")
        table.add_column("Value", style="yellow")
        
        table.add_row("Total Revenue", f"${stats['total']:.2f}")
        table.add_row("Revenue per Hour", f"${stats['total']/(stats['cycles']*2/60):.2f}")
        table.add_row("Revenue per Day", f"${stats['total']/(stats['cycles']*2/60/24):.2f}")
        table.add_row("ROI on $50", f"{((stats['total']/50)*100):.1f}%")
        
        self.console.print(table)
        input("\nPress Enter to continue...")
    
    def show_api_status(self):
        """Detailed API key status"""
        secrets, active_count = self.get_secrets_status()
        
        table = Table(title="πŸ”‘ API KEY DETAILS")
        table.add_column("Service", style="cyan")
        table.add_column("Status", style="green")
        table.add_column("Environment Variable", style="blue")
        
        for service, active in secrets.items():
            env_var = f"{service.upper()}_API_KEY"
            status = "βœ… ACTIVE" if active else "❌ MISSING"
            table.add_row(service, status, env_var)
        
        self.console.print(table)
        self.console.print(f"\n🎯 Active APIs: {active_count}/8")
        input("\nPress Enter to continue...")
    
    def show_system_health(self):
        """Show system health details"""
        system = self.get_system_status()
        
        table = Table(title="⚑ SYSTEM HEALTH")
        table.add_column("Component", style="cyan")
        table.add_column("Status", style="yellow")
        table.add_column("Details", style="green")
        
        table.add_row("vLLM (Elizabeth)", 
                     "βœ… ONLINE" if system['vllm'] else "❌ DOWN",
                     "Port 8000")
        
        table.add_row("DragonflyDB",
                     "βœ… ONLINE" if system['redis'] else "❌ DOWN",
                     "Port 18000")
        
        gpu = system['gpu']
        if gpu['utilization'] > 0:
            gpu_text = f"{gpu['utilization']}% | {gpu['memory_used']}MB/{gpu['memory_total']}MB"
            table.add_row("GPU H200", "βœ… ACTIVE", gpu_text)
        else:
            table.add_row("GPU H200", "❓ UNKNOWN", "Check nvidia-smi")
        
        self.console.print(table)
        input("\nPress Enter to continue...")
    
    def show_recent_activity(self):
        """Show recent cycles"""
        stats = self.get_earnings_stats()
        
        if not stats['recent']:
            self.console.print("[red]No recent activity[/red]")
            input("\nPress Enter to continue...")
            return
        
        table = Table(title="πŸ”„ RECENT CYCLES DETAILS")
        table.add_column("Time", style="cyan")
        table.add_column("Strategy", style="green")
        table.add_column("Earnings", style="yellow")
        table.add_column("GPU", style="purple")
        
        for timestamp, strategy, net, gpu in stats['recent']:
            time_str = datetime.datetime.fromisoformat(timestamp).strftime("%H:%M:%S")
            gpu_icon = "πŸš€ GPU" if gpu else "⚑ CPU"
            table.add_row(time_str, strategy, f"${net:.2f}", gpu_icon)
        
        self.console.print(table)
        input("\nPress Enter to continue...")
    
    def force_earnings_check(self):
        """Force immediate earnings calculation"""
        self.console.print("[yellow]πŸ”„ Forcing earnings check...[/yellow]")
        
        # Simulate a check
        current = self.get_live_earnings()
        self.console.print(f"[green]Current earnings: ${current:.2f}[/green]")
        
        input("\nPress Enter to continue...")
    
    def emergency_reset(self):
        """Emergency reset protocol"""
        confirm = input("πŸ’€ EMERGENCY RESET - Type 'DEATH' to confirm: ")
        if confirm == 'DEATH':
            self.console.print("[red]πŸ’€ Emergency reset initiated[/red]")
            # Reset database
            try:
                conn = sqlite3.connect(self.db_path)
                cursor = conn.cursor()
                cursor.execute('DELETE FROM revenue')
                conn.commit()
                conn.close()
                self.console.print("[green]βœ… Database reset complete[/green]")
            except Exception as e:
                self.console.print(f"[red]❌ Reset failed: {e}[/red]")
        else:
            self.console.print("[yellow]Reset cancelled[/yellow]")
        
        input("\nPress Enter to continue...")
    
    def launch_elizabeth_shell(self):
        """Launch Elizabeth interactive shell"""
        if not ELIZABETH_TOOLS_AVAILABLE:
            self.console.print("[red]❌ Elizabeth tools not available[/red]")
            input("\nPress Enter to continue...")
            return
        
        self.console.print("[green]πŸš€ Launching Elizabeth Shell...[/green]")
        try:
            subprocess.run(["python3", "elizabeth_shell.py"], cwd=os.getcwd())
        except Exception as e:
            self.console.print(f"[red]❌ Failed to launch shell: {e}[/red]")
        
        input("\nPress Enter to continue...")
    
    def execute_custom_command(self):
        """Execute custom shell command"""
        if not ELIZABETH_TOOLS_AVAILABLE:
            self.console.print("[red]❌ Elizabeth tools not available[/red]")
            input("\nPress Enter to continue...")
            return
        
        command = input("πŸ’€ Enter command to execute: ").strip()
        if not command:
            self.console.print("[yellow]❌ No command entered[/yellow]")
            input("\nPress Enter to continue...")
            return
        
        self.console.print(f"[yellow]πŸš€ Executing: {command}[/yellow]")
        result = execute_command(command, realtime=True)
        
        if result['success']:
            self.console.print(f"[green]βœ… SUCCESS ({(result['execution_time']):.2f}s)[/green]")
            if result['output']:
                self.console.print(f"[cyan]πŸ“‹ Output: {result['output'][:500]}{'...' if len(result['output']) > 500 else ''}[/cyan]")
        else:
            self.console.print(f"[red]❌ FAILED ({(result['execution_time']):.2f}s)[/red]")
            self.console.print(f"[red]πŸ’₯ Error: {result.get('output', 'Unknown error')}[/red]")
        
        input("\nPress Enter to continue...")
    
    def show_detailed_system_info(self):
        """Show detailed system information"""
        if not ELIZABETH_TOOLS_AVAILABLE:
            self.console.print("[red]❌ Elizabeth tools not available[/red]")
            input("\nPress Enter to continue...")
            return
        
        info = get_system_info()
        
        table = Table(title="⚑ DETAILED SYSTEM INFORMATION")
        table.add_column("Component", style="cyan")
        table.add_column("Value", style="yellow")
        
        for key, value in info.items():
            if value and not value.startswith("Error:") and not value.startswith("Exception:"):
                table.add_row(key, str(value))
        
        self.console.print(table)
        input("\nPress Enter to continue...")
    
    def run(self):
        """Run the interactive CLI"""
        while True:
            try:
                self.interactive_menu()
            except KeyboardInterrupt:
                self.console.print("\n[red]πŸ’€ Death March CLI terminated by user[/red]")
                break

if __name__ == "__main__":
    cli = DeathMarchCLI()
    cli.run()