import argparse
import threading
import time
import subprocess
import json
import urllib.request
import urllib.error

from .api import start_server

def run_test_request(host, port):
    url = f"http://{host}:{port}/health"
    print("\n[Test Mode] Waiting for server to initialize...")
    for _ in range(120): # Wait up to 240 seconds for huge models
        try:
            req = urllib.request.Request(url)
            with urllib.request.urlopen(req) as response:
                if response.getcode() == 200:
                    break
        except urllib.error.URLError:
            pass
        time.sleep(2)
    
    print("\n" + "="*50)
    print("[Test Mode] 🟢 Server healthy! Executing test query: 'how are you?'")
    print("="*50 + "\n")
    
    cmd = [
        "curl", "-N", "-s", "-X", "POST", f"http://{host}:{port}/v1/chat/completions",
        "-H", "Content-Type: application/json",
        "-d", json.dumps({
            "model": "Xoron-Test",
            "messages": [{"role": "user", "content": "how are you?"}],
            "max_tokens": 100,
            "stream": True # Streaming exactly as requested
        })
    ]
    subprocess.run(cmd)
    print("\n\n" + "="*50)
    print("[Test Mode] ✅ Auto-test completed. Server is available.")
    print("="*50 + "\n")

def main():
    parser = argparse.ArgumentParser(description="xorfice: Elite Multimodal Inference Server")
    parser.add_argument("--host", type=str, default="0.0.0.0", help="Host to bind to")
    parser.add_argument("--port", type=int, default=8000, help="Port to bind to")
    parser.add_argument("--weights", type=str, default="./weights", help="Path to local model weights")
    parser.add_argument("--hf", type=str, default=None, help="Hugging Face Model Repo ID (overrides --weights)")
    parser.add_argument("--test", action="store_true", help="Auto-run a curl test against the chat API after the server spins up")
    
    args = parser.parse_args()
    
    import os
    os.environ["XORON_MODEL_PATH"] = args.hf if args.hf else args.weights
    
    if args.test:
        test_thread = threading.Thread(target=run_test_request, args=(args.host, args.port), daemon=True)
        test_thread.start()
        
    print(f"📡 Starting xorfice server on {args.host}:{args.port}...")
    start_server(host=args.host, port=args.port)

if __name__ == "__main__":
    main()
