# BRYNQ SWARM - SECURE COMMAND LINE INTERFACE
# [AUTOGENERATED BY SYSTEM_ARCHITECT_01 | MISSION_100M]

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

def load_master_key():
    env_path = os.path.join(os.path.dirname(__file__), '..', '..', '.env')
    try:
        with open(env_path, 'r') as f:
            for line in f:
                if line.startswith('BRYNQ_MASTER_KEY='):
                    return line.split('=')[1].strip()
    except FileNotFoundError:
        pass
    return os.environ.get("BRYNQ_MASTER_KEY", "ZDtE-ALPHA-OMEGA-001")

def dispatch_command(directive: str):
    url = "http://127.0.0.1:8080/api/v1/orchestrate"
    key = load_master_key()
    
    payload = {
        "task_id": f"CLI-{int(time.time())}",
        "directive": directive,
        "complexity": "high"
    }
    
    headers = {
        'Content-Type': 'application/json',
        'X-BRYNQ-SWARM-AUTH': key
    }
    
    data = json.dumps(payload).encode('utf-8')
    req = urllib.request.Request(url, data=data, headers=headers, method='POST')
    
    try:
        print(f"\n[BRYNQ CLI] Authenticating with Swarm Gateway (Port 8080)...")
        with urllib.request.urlopen(req, timeout=10) as response:
            result = json.loads(response.read().decode())
            print(f"[BRYNQ CLI] SUCCESS. Payload Accepted by Multi-Model Router.")
            print(f"[ROUTER RESPONSE] -> {result.get('routing_decision')}\n")
    except urllib.error.HTTPError as e:
        print(f"\n[BRYNQ CLI] AUTHORIZATION FAILED: {e.code} - {e.reason}\n")
    except Exception as e:
        print(f"\n[BRYNQ CLI] FATAL: Swarm Gateway Offline. Execute 'boot_swarm.bat' first.\n")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: brynq \"Your command for the Swarm\"")
        sys.exit(1)
    
    directive = " ".join(sys.argv[1:])
    dispatch_command(directive)