#!/usr/bin/env python3
"""
Startup script for running both FastAPI and MCP servers
"""

import subprocess
import sys
import time
import signal

class ServerManager:
    def __init__(self):
        self.processes = []
        self.running = True

    def signal_handler(self, signum, frame):
        """Handle shutdown signals"""
        print("\nShutting down servers...")
        self.running = False
        for process in self.processes:
            try:
                process.terminate()
                process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                process.kill()
            except Exception:
                pass  # Process might already be dead
        sys.exit(0)

    def start_fastapi_server(self):
        """Start the FastAPI server"""
        print("Starting FastAPI server on port 8088...")
        process = subprocess.Popen([
            sys.executable, "-m", "uvicorn", "app.main:app",
            "--host", "0.0.0.0",
            "--port", "8088",
            "--reload"
        ])
        self.processes.append(process)
        return process

    # WebSocket server is now handled internally via FastAPI ws_routes.py

    def start_mcp_server(self):
        """Start the MCP server"""
        print("Starting MCP server on port 9099...")
        process = subprocess.Popen([
            sys.executable, "mcp_server.py"
        ])
        self.processes.append(process)
        return process

    def run(self):
        """Run all servers"""
        # Set up signal handlers
        signal.signal(signal.SIGINT, self.signal_handler)
        signal.signal(signal.SIGTERM, self.signal_handler)
        try:
            # Start FastAPI server
            fastapi_process = self.start_fastapi_server()

            # Wait a moment for FastAPI to start
            time.sleep(2)

            # Check if FastAPI started successfully
            if fastapi_process.poll() is not None:
                print("Failed to start FastAPI server")
                return

            print("FastAPI server started successfully!")

            # Start MCP server
            mcp_process = self.start_mcp_server()

            print("\n ================================================")
            print("  HITAS QUANT  |  All servers running")
            print(" ================================================")
            print("\n  PUBLIC (no login required)")
            print("  Home         http://localhost:8088/")
            print("  Login        http://localhost:8088/login")
            print("  Register     http://localhost:8088/register")
            print("\n  PAID PAGES (subscription required)")
            print("  Terminal     http://localhost:8088/nepse")
            print("  Charts       http://localhost:8088/advanced-charts")
            print("  Profile      http://localhost:8088/profile")
            print("  Signal Scan  http://localhost:8088/nepse-scan")
            print("  Health Scan  http://localhost:8088/health")
            print("  MS RSI Scan  http://localhost:8088/scanner")
            print("\n  ADMIN")
            print("  Dashboard    http://localhost:8088/admin-dashboard")
            print("\n  API")
            print("  Docs         http://localhost:8088/docs")
            print("  Health       http://localhost:8088/health")
            print("  WebSocket    ws://localhost:5566")
            print("\n  Press Ctrl+C to stop all servers.")
            print(" ------------------------------------------------")

            # Keep the main process alive
            while self.running:
                time.sleep(1)

                # Check if processes are still running
                if fastapi_process.poll() is not None:
                    print("FastAPI server stopped unexpectedly")
                    break
                if mcp_process.poll() is not None:
                    print("MCP server stopped unexpectedly")
                    break

        except KeyboardInterrupt:
            pass
        finally:
            self.signal_handler(None, None)

if __name__ == "__main__":
    manager = ServerManager()
    manager.run()
