#!/usr/bin/env python3
"""
Microbix Aether Team - Autonomous Local Execution Bridge (Desktop Runner)
========================================================================
Connects your local environment securely to Aether Team in the cloud.
Executes approved tasks, file edits, and terminal commands in your local directory.
"""

import os
import sys
import time
import json
import subprocess
import urllib.request
import urllib.error

VERSION = "1.0.0"
DEFAULT_API_BASE = "https://aether.microbix.in"

# Forbidden destructive commands for system safety
RISKY_PATTERNS = [
    "format ", "rmdir /s /q c:", "rm -rf /", "mkfs", "dd if=", 
    ":(){ :|:& };:", "del /f /s /q c:\\windows", "shutdown"
]

def print_banner():
    print("=" * 65)
    print("    MICROBIX AETHER TEAM — LOCAL EXECUTION BRIDGE v" + VERSION)
    print("=" * 65)
    print("  [Security]: Command Net Active (Manual Approval Enforced)")
    print("  [Protocol]: HTTPS / AES-256 Cloud Bridge")
    print("=" * 65)

def get_auth_key():
    key_file = os.path.expanduser("~/.aether_team_key")
    if os.path.exists(key_file):
        with open(key_file, "r") as f:
            k = f.read().strip()
            if k: return k
    print("\nPlease enter your Aether API Key (starts with mbx_live_):")
    k = input("Key: ").strip()
    if not k.startswith("mbx_live_"):
        print("[!] Warning: API Key should start with 'mbx_live_'.")
    try:
        with open(key_file, "w") as f:
            f.write(k)
    except:
        pass
    return k

def poll_team_tasks(api_base, api_key):
    url = f"{api_base}/api/team"
    req = urllib.request.Request(url, headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "User-Agent": f"AetherTeamRunner/{VERSION}"
    })
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            data = json.loads(resp.read().decode('utf-8'))
            return data
    except urllib.error.HTTPError as e:
        if e.code == 401:
            print("[!] Auth failed: Invalid API key.")
        return None
    except Exception as e:
        return None

def execute_command(cmd, work_dir):
    for risky in RISKY_PATTERNS:
        if risky in cmd.lower():
            return False, f"[Security Net Blocked]: Destructive pattern '{risky}' detected."

    target_dir = work_dir if os.path.exists(work_dir) else os.getcwd()
    print(f"\n[EXEC] Running: {cmd}")
    print(f"[PATH] Directory: {target_dir}")
    try:
        proc = subprocess.run(
            cmd,
            shell=True,
            cwd=target_dir,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            timeout=120
        )
        out = proc.stdout + ("\n" + proc.stderr if proc.stderr else "")
        return proc.returncode == 0, out
    except subprocess.TimeoutExpired:
        return False, "Command timed out after 120s."
    except Exception as e:
        return False, str(e)

def report_task_result(api_base, api_key, task_id, success, output):
    url = f"{api_base}/api/team/tasks/{task_id}/result"
    payload = json.dumps({
        "status": "COMPLETED" if success else "FAILED",
        "command_output": output
    }).encode('utf-8')
    req = urllib.request.Request(url, data=payload, headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "User-Agent": f"AetherTeamRunner/{VERSION}"
    })
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            return True
    except Exception as e:
        print(f"[!] Warning: Failed to report task result to server: {e}")
        return False

def main():
    print_banner()
    api_key = get_auth_key()
    api_base = os.environ.get("AETHER_API_BASE", DEFAULT_API_BASE)

    print(f"\n[*] Connecting to Aether Cloud Matrix: {api_base}...")
    team_data = poll_team_tasks(api_base, api_key)
    
    if not team_data or not team_data.get("exists"):
        print("[!] No active Aether Team found. Please configure your team on https://aether.microbix.in/team first.")
        input("\nPress Enter to exit...")
        sys.exit(1)

    team = team_data.get("team", {})
    company = team.get("company_name", "Aether Corp")
    work_dir = team.get("working_directory", os.getcwd())

    print(f"[✓] Linked to Team: {company}")
    print(f"[✓] Target Workspace: {work_dir}")
    print(f"[✓] Command Net: {team.get('command_approval_mode', 'MANUAL')}")
    print("\n[*] Listening for approved missions & subagent commands. Press Ctrl+C to stop.\n")

    while True:
        try:
            data = poll_team_tasks(api_base, api_key)
            if data and data.get("recent_tasks"):
                for task in data["recent_tasks"]:
                    if task.get("status") == "PENDING" and task.get("command_approved") and task.get("proposed_command"):
                        print(f"\n[>>>] Executing Approved Task: {task.get('title')}")
                        success, output = execute_command(task["proposed_command"], work_dir)
                        print(f"[<<<] Result: {'SUCCESS' if success else 'FAILED'}")
                        print(output[:300] + ("..." if len(output) > 300 else ""))
                        report_task_result(api_base, api_key, task["id"], success, output)
            time.sleep(4)
        except KeyboardInterrupt:
            print("\n[!] Bridge disconnected.")
            break
        except Exception as e:
            time.sleep(5)

if __name__ == "__main__":
    main()
