#!/usr/bin/env python3
"""
Archie Orchestrator CLI Chat
Simple command-line interface for chatting with Archie's Brain via WebSocket
"""

import asyncio
import websockets
import json
import sys
from pathlib import Path

# WebSocket URL (development)
WS_URL = "ws://localhost:3050/ws/orchestrator"

# Load JWT token if available
TOKEN_FILE = Path("/tmp/token.txt")


async def chat_session():
    """Run an interactive chat session with Archie's Brain"""

    # Load token
    token = None
    if TOKEN_FILE.exists():
        with open(TOKEN_FILE) as f:
            token = f.read().strip()
        print(f"✓ Using JWT token from {TOKEN_FILE}")
    else:
        print("⚠ No JWT token found, connecting anonymously")

    # Connect to WebSocket
    url = f"{WS_URL}?token={token}" if token else WS_URL

    print(f"\n🔌 Connecting to Archie's Brain at {WS_URL}...")

    try:
        async with websockets.connect(url, ping_interval=None) as websocket:
            # Wait for connection confirmation
            conn_msg = await websocket.recv()
            conn_data = json.loads(conn_msg)

            if conn_data.get("type") == "connected":
                print(f"✓ {conn_data.get('message')}")
                print(f"  User: {conn_data.get('user_id')}")
                print(f"  Time: {conn_data.get('timestamp')}")
                print("\n" + "="*70)
                print("💬 Chat with Archie (type 'exit' or 'quit' to end)")
                print("="*70 + "\n")

            conversation_id = None
            conversation_history = []

            while True:
                # Get user input
                try:
                    user_query = input("You: ").strip()
                except (EOFError, KeyboardInterrupt):
                    print("\n\n👋 Goodbye!")
                    break

                if not user_query:
                    continue

                if user_query.lower() in ['exit', 'quit', 'bye']:
                    print("\n👋 Goodbye!")
                    break

                # Send query
                query_msg = {
                    "type": "query",
                    "query": user_query,
                    "conversation_id": conversation_id,
                    "conversation_history": conversation_history
                }

                await websocket.send(json.dumps(query_msg))

                # Receive and display response
                print("\nArchie: ", end="", flush=True)

                full_response = ""
                error_occurred = False

                while True:
                    try:
                        response = await asyncio.wait_for(
                            websocket.recv(),
                            timeout=30.0
                        )

                        data = json.loads(response)
                        msg_type = data.get("type")

                        if msg_type == "chunk":
                            content = data.get("content", "")
                            print(content, end="", flush=True)
                            full_response += content

                        elif msg_type == "completed":
                            print("\n")

                            # Update conversation state
                            if not conversation_id:
                                conversation_id = data.get("conversation_id")

                            # Add to history
                            conversation_history.append({
                                "role": "user",
                                "content": user_query
                            })
                            conversation_history.append({
                                "role": "assistant",
                                "content": full_response
                            })

                            # Show metadata
                            confidence = data.get("confidence")
                            if confidence:
                                print(f"  [Confidence: {confidence:.2%}]")

                            break

                        elif msg_type == "error":
                            error_msg = data.get("error", "Unknown error")
                            print(f"\n❌ Error: {error_msg}\n")
                            error_occurred = True
                            break

                        elif msg_type == "progress":
                            # Optional: show progress indicators
                            status = data.get("status", "")
                            if status:
                                print(f"\n  [{status}]", end="", flush=True)

                    except asyncio.TimeoutError:
                        print("\n\n⏱️  Response timeout. Try again.")
                        error_occurred = True
                        break
                    except Exception as e:
                        print(f"\n\n❌ Error receiving response: {e}")
                        error_occurred = True
                        break

                if not error_occurred:
                    print()  # Extra newline for readability

    except websockets.exceptions.WebSocketException as e:
        print(f"❌ WebSocket error: {e}")
        print("\nIs the backend running on port 3050?")
        print("Try: curl http://localhost:3050/health")
        sys.exit(1)

    except Exception as e:
        print(f"❌ Unexpected error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)


def main():
    """Main entry point"""
    print("\n" + "="*70)
    print("🧠 Archie's Brain - CLI Chat Interface")
    print("="*70)

    try:
        asyncio.run(chat_session())
    except KeyboardInterrupt:
        print("\n\n👋 Interrupted. Goodbye!")


if __name__ == "__main__":
    main()
