#!/usr/bin/env python3
"""Smoke Test 1: Authorization Check

Tests that unauthorized access is properly denied by the device agent.

Usage:
    ./test_authorization.py <DEVICE_HASH>

This test should FAIL if you're not authorized (expected behavior).
To test authorization, add your identity hash to the device's auth.yaml first.
"""

import asyncio
import sys
from pathlib import Path

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))

from styrene.services.rpc_client import RPCClient
from styrene.services.lxmf_service import get_lxmf_service
from styrene.services.reticulum import initialize_reticulum, get_operator_identity_object


async def test_authorization(device_hash: str):
    """Test authorization enforcement.

    Args:
        device_hash: Target device identity hash
    """
    print("=" * 60)
    print("SMOKE TEST 1: Authorization Check")
    print("=" * 60)
    print()

    # Initialize Reticulum
    print("Initializing Reticulum...")
    initialize_reticulum(headless=True)
    identity = get_operator_identity_object()
    print(f"Operator identity: {identity.hexhash}")
    print()

    # Initialize LXMF
    print("Initializing LXMF service...")
    lxmf = get_lxmf_service()
    lxmf.initialize(identity)
    print()

    # Create RPC client
    print("Creating RPC client...")
    client = RPCClient(lxmf)
    print()

    # Try to execute command
    print(f"Attempting exec command to device: {device_hash}")
    print("(This should fail if not authorized - that's expected!)")
    print()

    try:
        result = await client.call_exec(
            device_hash,
            "echo",
            ["authorization test"],
            timeout=10.0
        )

        print("✓ AUTHORIZED: Command executed successfully")
        print(f"  Exit code: {result.exit_code}")
        print(f"  Output: {result.stdout.strip()}")
        print()
        print("SUCCESS: You are authorized on the device")
        return True

    except TimeoutError:
        print("✗ TIMEOUT: Device did not respond within 10 seconds")
        print()
        print("POSSIBLE CAUSES:")
        print("  1. Device is offline or unreachable")
        print("  2. Device agent is not running")
        print("  3. Network connectivity issues")
        return False

    except Exception as e:
        error_msg = str(e).lower()
        if "unauthorized" in error_msg or "permission" in error_msg:
            print("✗ DENIED: Unauthorized (this is expected behavior)")
            print(f"  Error: {e}")
            print()
            print("SUCCESS: Authorization is working correctly")
            print()
            print("TO AUTHORIZE THIS IDENTITY:")
            print(f"  1. Add '{identity.hexhash}' to device's auth.yaml")
            print("  2. Grant 'exec' permission")
            print("  3. Reload device agent: systemctl reload styrene-agent")
            return True
        else:
            print(f"✗ ERROR: Unexpected failure: {e}")
            return False


def main():
    """Main entry point."""
    if len(sys.argv) != 2:
        print("Usage: ./test_authorization.py <DEVICE_HASH>")
        print()
        print("Get device hash from device:")
        print("  rnstatus -i")
        sys.exit(1)

    device_hash = sys.argv[1]

    try:
        success = asyncio.run(test_authorization(device_hash))
        sys.exit(0 if success else 1)
    except KeyboardInterrupt:
        print("\nInterrupted")
        sys.exit(1)


if __name__ == "__main__":
    main()
