from flask import Flask, jsonify, request
import asyncio
import os
import websockets
import json
import uuid
from concurrent.futures import ThreadPoolExecutor
import threading

app = Flask(__name__)

# Config: map to your domain/host via env (same as websocket_server.py)
WEBSOCKET_HOST = os.getenv("WEBSOCKET_HOST", "10.0.0.109")
WEBSOCKET_PORT = os.getenv("WEBSOCKET_PORT", "7845")
WEBSOCKET_PATH = os.getenv("WEBSOCKET_PATH", "voicebot_session_2002")
UNIQUE_API_PORT = int(os.getenv("UNIQUE_API_PORT", "5005"))

def get_websocket_uri():
    return f"ws://{WEBSOCKET_HOST}:{WEBSOCKET_PORT}/ws/{WEBSOCKET_PATH}"

# Thread pool for running async WebSocket operations
executor = ThreadPoolExecutor(max_workers=10)

async def get_unique_id_from_websocket():
    """Connect to WebSocket server and get unique ID"""
    uri = get_websocket_uri()
    
    try:
        async with websockets.connect(uri) as websocket:
            # Wait for the unique ID from server
            response = await websocket.recv()
            data = json.loads(response)
            return {
                "success": True,
                "unique_id": data['unique_id'],
                "message": data['message'],
                "timestamp": data['timestamp'],
                "source": "websocket"
            }
    except websockets.exceptions.ConnectionRefused:
        return {
            "success": False,
            "error": "Could not connect to WebSocket server",
            "message": f"Make sure the WebSocket server is running on {WEBSOCKET_HOST}:{WEBSOCKET_PORT}"
        }
    except Exception as e:
        return {
            "success": False,
            "error": str(e),
            "message": "WebSocket connection failed"
        }

def run_async_websocket():
    """Run the async WebSocket function in a new event loop"""
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        return loop.run_until_complete(get_unique_id_from_websocket())
    finally:
        loop.close()

@app.route('/get-unique-id', methods=['GET'])
def get_unique_id():
    """API endpoint to get unique ID from WebSocket"""
    try:
        # Run the async WebSocket operation in a thread
        result = executor.submit(run_async_websocket).result(timeout=10)
        return jsonify(result)
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e),
            "message": "Failed to get unique ID"
        }), 500

@app.route('/generate-local-id', methods=['GET'])
def generate_local_id():
    """Fallback endpoint that generates unique ID locally"""
    unique_id = str(uuid.uuid4())
    return jsonify({
        "success": True,
        "unique_id": unique_id,
        "message": "Generated locally",
        "timestamp": str(asyncio.get_event_loop().time()) if asyncio.get_event_loop().is_running() else "N/A",
        "source": "local"
    })

@app.route('/health', methods=['GET'])
def health_check():
    """Health check endpoint"""
    return jsonify({
        "status": "healthy",
        "message": "API server is running",
        "websocket_url": get_websocket_uri()
    })

@app.route('/', methods=['GET'])
def home():
    """Home endpoint with API documentation"""
    return jsonify({
        "message": "Unique ID API Server",
        "endpoints": {
            "/get-unique-id": "GET - Get unique ID from WebSocket server",
            "/generate-local-id": "GET - Generate unique ID locally (fallback)",
            "/health": "GET - Health check",
            "/": "GET - This documentation"
        },
        "websocket_url": get_websocket_uri(),
        "example_curl": f"curl http://localhost:{UNIQUE_API_PORT}/get-unique-id"
    })

if __name__ == '__main__':
    import socket
    
    # Get system IP address
    def get_local_ip():
        try:
            # Connect to a remote address to get local IP
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            local_ip = s.getsockname()[0]
            s.close()
            return local_ip
        except:
            return "127.0.0.1"
    
    system_ip = get_local_ip()
    
    print("Starting Unique ID API Server...")
    print("Available endpoints:")
    print("  GET /get-unique-id     - Get unique ID from WebSocket")
    print("  GET /generate-local-id - Generate unique ID locally")
    print("  GET /health           - Health check")
    print("  GET /                 - API documentation")
    print(f"\nSystem IP: {system_ip}")
    print(f"\nExample curl commands:")
    print(f"  curl http://{system_ip}:{UNIQUE_API_PORT}/get-unique-id")
    print(f"  curl http://localhost:{UNIQUE_API_PORT}/get-unique-id")
    print(f"\nServer starting on:")
    print(f"  http://{system_ip}:{UNIQUE_API_PORT}")
    print(f"  http://localhost:{UNIQUE_API_PORT}")
    
    app.run(debug=False, host='0.0.0.0', port=UNIQUE_API_PORT)
