#!/usr/bin/env python3
"""Simple test script to verify backend functionality."""
import asyncio
import sys
from pathlib import Path

# Add app to path
sys.path.insert(0, str(Path(__file__).parent))

from app.backend.workers.pm3_worker import MockPM3Worker
from app.backend.managers.session_manager import SessionManager


async def test_pm3_worker():
    """Test PM3 worker with mock."""
    print("\n🧪 Testing PM3 Worker (Mock)...")

    worker = MockPM3Worker()

    # Test connection
    await worker.connect()
    is_connected = await worker.is_connected()
    print(f"  ✓ Connection: {'connected' if is_connected else 'disconnected'}")

    # Test commands
    commands = ["hw version", "hw status", "hw tune"]
    for cmd in commands:
        result = await worker.execute_command(cmd)
        print(f"  ✓ Command '{cmd}': {'success' if result.success else 'failed'}")
        if result.output:
            print(f"    Output: {result.output[:60]}...")

    await worker.disconnect()
    print("  ✓ Disconnected")


async def test_session_manager():
    """Test session manager."""
    print("\n🧪 Testing Session Manager...")

    manager = SessionManager()

    # Test creating session
    success, session_id, error = await manager.create_session("127.0.0.1", "test-agent")
    print(f"  ✓ Created session: {session_id}")

    # Test has active session
    has_active = manager.has_active_session()
    print(f"  ✓ Has active session: {has_active}")

    # Test can execute
    can_execute = manager.can_execute(session_id)
    print(f"  ✓ Can execute: {can_execute}")

    # Test creating second session (should fail)
    success2, session_id2, error2 = await manager.create_session("127.0.0.2", "test-agent-2")
    print(f"  ✓ Second session blocked: {not success2}")
    print(f"    Error: {error2}")

    # Test takeover
    success3, session_id3, error3 = await manager.create_session(
        "127.0.0.3", "test-agent-3", force_takeover=True
    )
    print(f"  ✓ Takeover successful: {success3}")
    print(f"    New session: {session_id3}")

    # Release session
    released = await manager.release_session(session_id3)
    print(f"  ✓ Session released: {released}")


async def main():
    """Run all tests."""
    print("=" * 60)
    print("Dangerous Pi Backend - Component Tests")
    print("=" * 60)

    try:
        await test_pm3_worker()
        await test_session_manager()

        print("\n" + "=" * 60)
        print("✅ All tests passed!")
        print("=" * 60)
        print("\nTo start the backend server, run:")
        print("  python -m app.backend.main")
        print("\nOr:")
        print("  uvicorn app.backend.main:app --reload --host 0.0.0.0 --port 8000")

    except Exception as e:
        print(f"\n❌ Test failed: {e}")
        import traceback
        traceback.print_exc()
        return 1

    return 0


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