"""
Entrypoint for running ScrAIbe as a module:

    python -m scraibe

Always launches the Web GUI (Gradio).
Optionally launches:
- MCP-style API server
- Watch-folder mode
"""

import os
import threading
import logging

logger = logging.getLogger("scraibe.__main__")

from .webui import create_app


def _run_mcp_server():
    """
    Run MCP server in a separate thread.
    """
    import uvicorn
    from . import mcp_server

    host = os.getenv("MCP_SERVER_HOST", "0.0.0.0")
    port = int(os.getenv("MCP_SERVER_PORT", "8000"))

    uvicorn.run(
        mcp_server.app,
        host=host,
        port=port,
        log_level="info",
    )


if __name__ == "__main__":
    # Optionally start MCP server in background (non-blocking)
    mcp_enabled = os.getenv("MCP_SERVER_ENABLED", "false").strip().lower() in ("true", "1", "yes")
    if mcp_enabled:
        try:
            t = threading.Thread(target=_run_mcp_server, daemon=True)
            t.start()
            logger.info("MCP server started in background.")
        except Exception as e:
            logger.warning("Failed to start MCP server (WebUI will continue): %s", e)

    # Optionally start watch-folder mode (non-blocking)
    try:
        from .watcher import start_watcher
        start_watcher()
        logger.info("Watch-folder mode started.")
    except Exception as e:
        logger.warning("Failed to start watch-folder mode (WebUI will continue): %s", e)

    # Always start WebUI (Gradio)
    create_app()
