#!/usr/bin/env python3
"""Example: Using Styrene services standalone (without TUI).

This demonstrates how to initialize and use Styrene functionality
from Python scripts, tests, or other tools.
"""

import logging
import sys
from time import sleep

from styrene.services.app_lifecycle import get_service_status, initialize_styrene
from styrene.services.fleet import get_fleet_summary, load_inventory
from styrene.services.hardware import get_disks, get_network_interfaces, get_system_info
from styrene.services.reticulum import discover_devices, get_styrene_devices, start_discovery


def setup_logging():
    """Configure logging for the example."""
    logging.basicConfig(
        level=logging.INFO,
        format="[%(levelname)s] %(message)s",
    )


def show_system_hardware():
    """Show system hardware information."""
    print("\n=== SYSTEM HARDWARE ===")

    try:
        # System info
        info = get_system_info()
        print(f"CPU: {info.cpu_model}")
        print(f"Cores: {info.cpu_cores}")
        print(f"RAM: {info.ram_total_gb:.1f} GB")

        # Disks
        disks = get_disks()
        removable = [d for d in disks if d.is_removable]
        print(f"Disks: {len(disks)} total, {len(removable)} removable")

        # Network
        interfaces = get_network_interfaces()
        hardware = [i for i in interfaces if i.is_hardware]
        active = [i for i in hardware if i.is_up]
        print(f"Network: {len(active)}/{len(hardware)} interfaces up")

    except Exception as e:
        print(f"Hardware detection error: {e}")


def show_fleet_status():
    """Show fleet status."""
    print("\n=== FLEET STATUS ===")

    try:
        summary = get_fleet_summary()
        print(f"Online:  {summary['online']}")
        print(f"Offline: {summary['offline']}")
        print(f"Pending: {summary['pending']}")
        print(f"Total:   {summary['total']}")

        # Show device details
        devices = load_inventory()
        if devices:
            print("\nDevices:")
            for device in devices[:5]:  # Show first 5
                print(f"  {device.name:<20} {device.status:<10} {device.ip_address or '--'}")
            if len(devices) > 5:
                print(f"  ... and {len(devices) - 5} more")

    except Exception as e:
        print(f"Fleet unavailable: {e}")


def show_reticulum_status():
    """Show Reticulum service status."""
    print("\n=== RETICULUM STATUS ===")

    status = get_service_status()

    print(f"RNS Initialized: {status['rns_initialized']}")
    print(f"Operator Identity: {status['operator_identity'] or 'not set'}")
    print(f"Transport Enabled: {status['transport_enabled']}")
    print(f"Interface Count: {status['interface_count']}")
    print(f"Hub Connected: {status['hub_connected']}")
    if status['hub_address']:
        print(f"Hub Address: {status['hub_address'][:16]}...")


def run_device_discovery(duration_seconds: int = 30):
    """Run device discovery for specified duration."""
    print(f"\n=== DEVICE DISCOVERY ({duration_seconds}s) ===")

    discovered_count = [0]  # Use list for closure

    def on_device_discovered(device_info):
        """Callback for discovered devices."""
        discovered_count[0] += 1
        is_styrene = device_info.get("is_styrene", False)
        marker = "✓" if is_styrene else "○"
        name = device_info.get("name", "unknown")
        identity = device_info.get("identity", "")[:16]

        print(f"{marker} {name:<20} {identity}...")

    # Start discovery
    start_discovery(callback=on_device_discovered)
    print("Listening for announces...")

    # Run for specified duration
    sleep(duration_seconds)

    # Show summary
    all_devices = discover_devices()
    styrene_devices = get_styrene_devices()

    print("\nDiscovery Summary:")
    print(f"  Total devices: {len(all_devices)}")
    print(f"  Styrene devices: {len(styrene_devices)}")


def main():
    """Main entry point."""
    setup_logging()

    print("=" * 60)
    print("Styrene Standalone Example")
    print("=" * 60)

    # Initialize Styrene services
    print("\nInitializing services...")
    lifecycle = initialize_styrene()

    if not lifecycle.is_initialized:
        print("✗ Failed to initialize services")
        return 1

    print("✓ Services initialized")

    try:
        # Show various status information
        show_system_hardware()
        show_fleet_status()
        show_reticulum_status()

        # Optionally run device discovery
        # Uncomment to test discovery (requires RNS configured):
        # run_device_discovery(duration_seconds=30)

        print("\n" + "=" * 60)
        print("✓ Example complete")
        print("=" * 60)

    finally:
        # Always cleanup
        print("\nShutting down services...")
        lifecycle.shutdown()
        print("✓ Shutdown complete")

    return 0


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