"""Live integration test for the Sandbox HTTP client.

Usage:
    python -m tests.test_live_sandbox

Requires a running sandbox service at the configured address.
"""

from __future__ import annotations

import sys
import time

from flash_sandbox import HTTPClient

ADDRESS = "http://140.238.223.116:8092/v1/service/sandbox"
SANDBOX_TYPE = "docker"
SANDBOX_IMAGE = "ubuntu:22.04"


def main() -> int:
    print(f"Connecting to sandbox service at {ADDRESS}")
    client = HTTPClient(address=ADDRESS, timeout=60.0)

    sandbox_id = None
    try:
        # -- 1. Start a sandbox -------------------------------------------
        print("\n[1/6] Starting sandbox...")
        sandbox_id = client.start_sandbox(
            type=SANDBOX_TYPE,
            image=SANDBOX_IMAGE,
            command=["sleep", "infinity"],
            memory_mb=512,
            cpu_cores=1.0,
        )
        print(f"  ✓ Sandbox started: {sandbox_id}")

        # Give it a moment to fully initialise
        time.sleep(2)

        # -- 2. Check status ----------------------------------------------
        print("\n[2/6] Checking status...")
        status = client.get_status(sandbox_id)
        print(f"  ✓ Status: {status}")
        assert status.lower() == "running", f"Expected 'running', got '{status}'"

        # -- 3. Execute a simple command ----------------------------------
        print("\n[3/6] Executing command: echo 'Hello from sandbox'")
        result = client.exec_command(sandbox_id, ["echo", "Hello from sandbox"])
        print(f"  ✓ stdout:    {result.stdout!r}")
        print(f"    stderr:    {result.stderr!r}")
        print(f"    exit_code: {result.exit_code}")
        assert result.exit_code == 0, f"Expected exit_code 0, got {result.exit_code}"
        assert "Hello from sandbox" in result.stdout, f"Unexpected stdout: {result.stdout!r}"

        # -- 4. Execute a command that writes to stderr -------------------
        print("\n[4/6] Executing command: ls /nonexistent")
        result = client.exec_command(sandbox_id, ["ls", "/nonexistent"])
        print(f"  ✓ stdout:    {result.stdout!r}")
        print(f"    stderr:    {result.stderr!r}")
        print(f"    exit_code: {result.exit_code}")
        assert result.exit_code != 0, "Expected non-zero exit_code for missing path"

        # -- 5. Retrieve metrics ------------------------------------------
        print("\n[5/6] Fetching metrics...")
        try:
            metrics = client.get_metrics(sandbox_id)
            print(f"  ✓ memory_usage_bytes: {metrics.memory_usage_bytes}")
            print(f"    memory_limit_bytes: {metrics.memory_limit_bytes}")
            print(f"    memory_percent:     {metrics.memory_percent:.2f}%")
            print(f"    cpu_percent:        {metrics.cpu_percent:.2f}%")
            print(f"    pids_current:       {metrics.pids_current}")
            print(f"    net_rx_bytes:       {metrics.net_rx_bytes}")
            print(f"    net_tx_bytes:       {metrics.net_tx_bytes}")
            print(f"    block_read_bytes:   {metrics.block_read_bytes}")
            print(f"    block_write_bytes:  {metrics.block_write_bytes}")
        except Exception as exc:
            # Metrics may not be supported by all backends; warn but don't fail.
            print(f"  ⚠ Metrics unavailable: {exc}")

        # -- 6. Stop the sandbox ------------------------------------------
        print("\n[6/6] Stopping sandbox...")
        client.stop_sandbox(sandbox_id)
        sandbox_id = None  # prevent double-cleanup
        print("  ✓ Sandbox stopped and removed")

        print("\n" + "=" * 50)
        print("All checks passed!")
        print("=" * 50)
        return 0

    except Exception as exc:
        print(f"\n✗ Test failed: {exc}", file=sys.stderr)
        import traceback
        traceback.print_exc()
        return 1

    finally:
        # Best-effort cleanup
        if sandbox_id is not None:
            print(f"\nCleaning up sandbox {sandbox_id}...")
            try:
                client.stop_sandbox(sandbox_id)
                print("  ✓ Cleanup complete")
            except Exception as cleanup_exc:
                print(f"  ⚠ Cleanup failed: {cleanup_exc}", file=sys.stderr)
        client.close()


if __name__ == "__main__":
    raise SystemExit(main())
