"""
Railway start script for DcisionAI MCP Server

This script initializes logging and starts the FastMCP server
with Railway-specific configuration (PORT, HOST, etc.)
"""

import os
import sys
import logging

# Configure logging
logging.basicConfig(
    level=os.getenv("DCISIONAI_LOG_LEVEL", "INFO"),
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


def main():
    """Start the MCP server"""
    logger.info("🚀 Starting DcisionAI MCP Server on Railway")
    logger.info(f"Domain Filter: {os.getenv('DCISIONAI_DOMAIN_FILTER', 'all')}")
    logger.info(f"API URL: {os.getenv('DCISIONAI_API_URL', 'http://localhost:8000')}")
    
    # Railway provides PORT env var
    port = int(os.getenv("PORT", "8080"))
    host = os.getenv("HOST", "0.0.0.0")
    
    logger.info(f"Starting server on {host}:{port}")
    
    try:
        from dcisionai_mcp_server.fastmcp_server import mcp, app
        import uvicorn
        
        logger.info("✅ FastMCP server imported successfully")
        
        # If we have a FastAPI app with health endpoint, use uvicorn directly
        # Otherwise, let FastMCP handle it
        if app:
            logger.info("✅ Using FastAPI app with health endpoint")
            logger.info(f"🚀 Starting server on {host}:{port}")
            uvicorn.run(app, host=host, port=port, log_level="info")
        else:
            logger.info("⚠️  No FastAPI app wrapper, using FastMCP.run()")
            logger.info(f"🚀 Starting FastMCP server on {host}:{port}")
            # FastMCP.run() may not accept host/port, so we'll let it use defaults
            # Railway's PORT env var should be picked up automatically
            mcp.run()
    except Exception as e:
        logger.error(f"❌ Failed to start MCP server: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()
