#!/usr/bin/env python3
"""
Setup script for Matrix: register user and create room
"""
import asyncio
import os
from nio import AsyncClient, RegisterResponse, RoomCreateResponse

async def setup_matrix():
    homeserver = "http://124.local:8008"
    username = "einszwovier"
    password = "einszwo4"

    client = AsyncClient(homeserver)

    print("🔧 Setting up Matrix server...")
    print(f"   Homeserver: {homeserver}")
    print(f"   Username: {username}")

    # Register the user
    print("\n📝 Registering user...")
    response = await client.register(
        username=username,
        password=password
    )

    if isinstance(response, RegisterResponse):
        print(f"   ✅ User registered: {response.user_id}")
        user_id = response.user_id
    else:
        print(f"   ℹ️  User might already exist, trying to login...")
        # Try to login instead
        response = await client.login(password)
        if response.user_id:
            print(f"   ✅ Logged in as: {response.user_id}")
            user_id = response.user_id
        else:
            print(f"   ❌ Failed: {response}")
            await client.close()
            return

    # Create a room
    print("\n🏠 Creating print orders room...")
    response = await client.room_create(
        name="Print Orders",
        topic="PDF print order submissions from the web app",
        is_public=False
    )

    if isinstance(response, RoomCreateResponse):
        print(f"   ✅ Room created!")
        print(f"   Room ID: {response.room_id}")
        print(f"\n✅ Setup complete!")
        print(f"\n📋 Add this to your .env file:")
        print(f"MATRIX_ROOM={response.room_id}")
    else:
        print(f"   ❌ Failed to create room: {response}")

    await client.close()

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