"""Gateway client for CLI command submission."""
import requests
import time
from typing import Optional, Dict, Any

class GatewayClient:
    def __init__(self, gateway_url: str, device_token: str):
        self.gateway_url = gateway_url.rstrip('/')
        # Strip "Device " prefix if user included it
        token = device_token.replace("Device ", "", 1).strip()
        self.device_token = token
        self.headers = {"Authorization": f"Device {token}"}
        
    def submit_action(self, command: str) -> Optional[str]:
        """Submit command to gateway and return action_id."""
        url = f"{self.gateway_url}/agent/actions/submit"
        payload = {"action_input": command}
        
        try:
            resp = requests.post(url, json=payload, headers=self.headers, timeout=10)
            if resp.status_code in [200, 201]:
                data = resp.json()
                return data.get("action_id")
            else:
                print(f"[Gateway Error] Status {resp.status_code}: {resp.text}")
        except requests.exceptions.ConnectionError:
            print(f"[Gateway Error] Cannot connect to {self.gateway_url}")
        except requests.exceptions.Timeout:
            print(f"[Gateway Error] Request timeout")
        except Exception as e:
            print(f"[Gateway Error] {type(e).__name__}: {e}")
        return None
    
    def get_action_status(self, action_id: str) -> Optional[Dict[str, Any]]:
        """Get action status from gateway."""
        url = f"{self.gateway_url}/agent/actions/{action_id}/status"
        
        try:
            resp = requests.get(url, headers=self.headers, timeout=10)
            if resp.status_code == 200:
                return resp.json()
        except:
            pass
        return None
    
    def wait_for_completion(self, action_id: str, timeout: int = 300) -> Dict[str, Any]:
        """Wait for action to complete and return result."""
        start_time = time.time()
        
        while time.time() - start_time < timeout:
            status_data = self.get_action_status(action_id)
            
            if not status_data:
                time.sleep(1)
                continue
            
            status = status_data.get("status")
            
            if status == "COMPLETED":
                result = status_data.get("result", "")
                if isinstance(result, dict):
                    result = result.get("message", str(result))
                return {
                    "success": True,
                    "result": result or "Command completed successfully",
                    "status": status
                }
            elif status == "FAILED":
                error = status_data.get("error", "")
                if isinstance(error, dict):
                    error = error.get("message", str(error))
                return {
                    "success": False,
                    "error": error or "Command failed (gateway did not return error details)",
                    "status": status
                }
            
            time.sleep(1)
        
        return {
            "success": False,
            "error": "Timeout waiting for command execution",
            "status": "TIMEOUT"
        }
    
    def test_connection(self) -> bool:
        """Test connection to gateway."""
        try:
            resp = requests.get(f"{self.gateway_url}/health", timeout=5)
            return resp.status_code == 200
        except:
            return False
