#!/usr/bin/env python3
"""
Test Matrix connection from host machine perspective
"""
import asyncio
import os
from nio import AsyncClient


async def test_connection(homeserver_url: str):
    """Test connection to Matrix homeserver"""
    print(f"\n🔍 Testing connection to: {homeserver_url}")

    matrix_user = os.environ.get("MATRIX_USER", "@einszwovier:124.local")
    matrix_pass = os.environ.get("MATRIX_PASS", "einszwo4")

    client = AsyncClient(homeserver_url, matrix_user)

    try:
        print(f"   User: {matrix_user}")
        print(f"   Attempting login...")

        resp = await client.login(matrix_pass)

        if hasattr(resp, 'access_token'):
            print(f"   ✅ SUCCESS! Logged in as {matrix_user}")
            print(f"   Device ID: {resp.device_id}")
            await client.logout()
        else:
            print(f"   ❌ FAILED: {resp}")

    except Exception as e:
        print(f"   ❌ ERROR: {e}")
    finally:
        await client.close()


async def main():
    print("=" * 60)
    print("Matrix Connection Test")
    print("=" * 60)

    # Test different homeserver URLs
    test_urls = [
        "http://localhost:8008",
        "http://127.0.0.1:8008",
        "http://124.local:8008",
    ]

    for url in test_urls:
        await test_connection(url)

    print("\n" + "=" * 60)
    print("Recommendation:")
    print("If localhost/127.0.0.1 works but 124.local fails,")
    print("configure Element to use: http://localhost:8008")
    print("=" * 60)


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