#!/usr/bin/env python3
"""Smoke Test 2: Status Request

Tests that status requests work and return expected device information.

Usage:
    ./test_status.py <DEVICE_HASH>

Requirements:
    - Device agent must be running
    - Your identity must be authorized for 'status_request' permission
"""

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_status(device_hash: str):
    """Test status request.

    Args:
        device_hash: Target device identity hash
    """
    print("=" * 60)
    print("SMOKE TEST 2: Status Request")
    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()

    # Request status
    print(f"Requesting status from device: {device_hash}")
    print("Waiting for response (timeout: 15s)...")
    print()

    try:
        status = await client.call_status(device_hash, timeout=15.0)

        print("✓ SUCCESS: Received status response")
        print()
        print("DEVICE STATUS:")
        print("-" * 60)
        print(f"  Uptime:       {status.uptime} seconds ({status.uptime / 3600:.1f} hours)")
        print(f"  IP Address:   {status.ip}")
        print(f"  Disk Used:    {status.disk_used / (1024**3):.2f} GB")
        print(f"  Disk Total:   {status.disk_total / (1024**3):.2f} GB")
        print(f"  Disk Usage:   {(status.disk_used / status.disk_total * 100):.1f}%")
        print()

        if status.services:
            print("  Services:")
            for service in status.services:
                print(f"    - {service}")
        else:
            print("  Services:     (none reported)")

        print("-" * 60)
        print()

        # Validation checks
        issues = []

        if status.uptime < 60:
            issues.append("WARN: Device recently rebooted (uptime < 1 minute)")

        disk_usage_pct = (status.disk_used / status.disk_total * 100)
        if disk_usage_pct > 90:
            issues.append(f"WARN: Disk usage high ({disk_usage_pct:.1f}%)")
        elif disk_usage_pct > 80:
            issues.append(f"INFO: Disk usage moderate ({disk_usage_pct:.1f}%)")

        if not status.services:
            issues.append("INFO: No services reported (expected?)")

        if issues:
            print("OBSERVATIONS:")
            for issue in issues:
                print(f"  {issue}")
            print()

        print("✓ Status check PASSED")
        return True

    except TimeoutError:
        print("✗ TIMEOUT: Device did not respond within 15 seconds")
        print()
        print("TROUBLESHOOTING:")
        print("  1. Verify device agent is running:")
        print("     systemctl status styrene-agent")
        print()
        print("  2. Check device logs:")
        print("     journalctl -u styrene-agent -f")
        print()
        print("  3. Verify network connectivity:")
        print("     rnstatus")
        print()
        print("  4. Confirm device hash is correct:")
        print("     (on device) rnstatus -i")
        return False

    except Exception as e:
        error_msg = str(e).lower()
        if "unauthorized" in error_msg or "permission" in error_msg:
            print(f"✗ UNAUTHORIZED: {e}")
            print()
            print("RESOLUTION:")
            print(f"  Add '{identity.hexhash}' to device auth.yaml with 'status_request' permission")
            return False
        else:
            print(f"✗ ERROR: {e}")
            import traceback
            traceback.print_exc()
            return False


def main():
    """Main entry point."""
    if len(sys.argv) != 2:
        print("Usage: ./test_status.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_status(device_hash))
        sys.exit(0 if success else 1)
    except KeyboardInterrupt:
        print("\nInterrupted")
        sys.exit(1)


if __name__ == "__main__":
    main()
