#!/usr/bin/env python3
"""
GuruRMM API Access Test Script

Tests the newly created admin user credentials and verifies API access.
"""

import requests
import json
from datetime import datetime
from vault_utils import vault_get

# Configuration - credentials from SOPS vault
API_BASE_URL = "http://172.16.3.30:3001"
EMAIL = vault_get("infrastructure/gururmm-server.sops.yaml", "credentials.gururmm-api.admin-email")
PASSWORD = vault_get("infrastructure/gururmm-server.sops.yaml", "credentials.gururmm-api.admin-password")

def print_header(title):
    """Print a formatted header."""
    print("\n" + "=" * 60)
    print(f"  {title}")
    print("=" * 60 + "\n")

def print_success(message):
    """Print success message."""
    print(f"[OK] {message}")

def print_error(message):
    """Print error message."""
    print(f"[ERROR] {message}")

def test_login():
    """Test login and retrieve JWT token."""
    print_header("Test 1: Login and Authentication")

    try:
        response = requests.post(
            f"{API_BASE_URL}/api/auth/login",
            json={"email": EMAIL, "password": PASSWORD},
            timeout=10
        )

        if response.status_code != 200:
            print_error(f"Login failed with status {response.status_code}")
            print(f"Response: {response.text}")
            return None

        data = response.json()
        token = data.get("token")
        user = data.get("user")

        if not token:
            print_error("No token in response")
            return None

        print_success("Login successful")
        print(f"  User ID: {user.get('id')}")
        print(f"  Email: {user.get('email')}")
        print(f"  Name: {user.get('name')}")
        print(f"  Role: {user.get('role')}")
        print(f"  Token: {token[:50]}...")

        return token

    except requests.exceptions.RequestException as e:
        print_error(f"Request failed: {e}")
        return None

def test_authenticated_request(token, endpoint, name):
    """Test an authenticated API request."""
    print_header(f"Test: {name}")

    try:
        headers = {"Authorization": f"Bearer {token}"}
        response = requests.get(
            f"{API_BASE_URL}{endpoint}",
            headers=headers,
            timeout=10
        )

        if response.status_code != 200:
            print_error(f"Request failed with status {response.status_code}")
            print(f"Response: {response.text}")
            return False

        data = response.json()
        count = len(data) if isinstance(data, list) else 1

        print_success(f"Retrieved {count} record(s)")

        # Print first record as sample
        if isinstance(data, list) and data:
            print("\nSample record:")
            print(json.dumps(data[0], indent=2))
        elif isinstance(data, dict):
            print("\nResponse:")
            print(json.dumps(data, indent=2)[:500] + "...")

        return True

    except requests.exceptions.RequestException as e:
        print_error(f"Request failed: {e}")
        return False

def main():
    """Main test runner."""
    print_header("GuruRMM API Access Test")
    print(f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"API Base URL: {API_BASE_URL}")
    print(f"Test User: {EMAIL}")

    # Test 1: Login
    token = test_login()
    if not token:
        print_error("Login test failed. Aborting remaining tests.")
        return 1

    # Test 2: Sites endpoint
    if not test_authenticated_request(token, "/api/sites", "List Sites"):
        print_error("Sites test failed")
        return 1

    # Test 3: Agents endpoint
    if not test_authenticated_request(token, "/api/agents", "List Agents"):
        print_error("Agents test failed")
        return 1

    # Test 4: Clients endpoint
    if not test_authenticated_request(token, "/api/clients", "List Clients"):
        print_error("Clients test failed")
        return 1

    # Success summary
    print_header("All Tests Passed!")
    print("API Credentials:")
    print(f"  Email: {EMAIL}")
    print(f"  Password: ********** (from vault)")
    print(f"  Base URL: {API_BASE_URL}")
    print(f"  Production URL: https://rmm-api.azcomputerguru.com")
    print("\nStatus: READY FOR INTEGRATION")
    print()

    return 0

if __name__ == "__main__":
    exit(main())
