#!/usr/bin/env python3
"""DataBridge Graph API Gateway — Entry point.

Initializes the MCP tool registry (same way as src/server.py) then
starts the FastAPI gateway on port 8090.

Usage:
    python run_gateway.py
    python run_gateway.py --port 8090 --host 0.0.0.0
"""

from __future__ import annotations

import argparse
import logging
import os
import sys
from pathlib import Path

# Ensure project root is on sys.path so src.* imports work
_project_root = Path(__file__).resolve().parent.parent.parent
if str(_project_root) not in sys.path:
    sys.path.insert(0, str(_project_root))

# Also add the gateway package src
_gateway_src = Path(__file__).resolve().parent / "src"
if str(_gateway_src) not in sys.path:
    sys.path.insert(0, str(_gateway_src))

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
)
logger = logging.getLogger("databridge.gateway")


def _bootstrap_registries():
    """Bootstrap DynamicToolRegistry and TenantRegistry from existing infrastructure.

    Reuses the same initialization path as src/server.py — imports the already-
    initialized module-level singletons.
    """
    dynamic_registry = None
    tenant_registry = None

    # Try importing the fully-initialized registries from src/server.py
    try:
        from src.server import _dynamic_registry, mcp
        dynamic_registry = _dynamic_registry
        logger.info(
            "Loaded DynamicToolRegistry from src/server: %d tools",
            dynamic_registry.total_count,
        )
    except ImportError:
        logger.info("src/server not importable — bootstrapping standalone registry")
        dynamic_registry = _bootstrap_standalone()

    # Load tenant registry
    try:
        from src.tenancy import TenantRegistry
        from src.config import settings
        tenant_registry = TenantRegistry(data_dir=Path(settings.data_dir) / "tenants")
        logger.info("TenantRegistry loaded from src/tenancy")
    except ImportError:
        logger.info("Tenant system not available — running single-tenant mode")

    return dynamic_registry, tenant_registry


def _bootstrap_standalone():
    """Standalone bootstrap when src/server.py is not available.

    Creates a fresh FastMCP instance, loads plugins, and builds the
    DynamicToolRegistry. This path is useful for isolated gateway testing.
    """
    try:
        from fastmcp import FastMCP
        from src.config import settings
        from src.plugins.dynamic_registry import DynamicToolRegistry
        from src.plugins.loader import load_all_plugins

        mcp = FastMCP("DataBridge AI Gateway Bootstrap")
        tool_mode = os.environ.get("DATABRIDGE_TOOL_MODE", "full")
        registry = DynamicToolRegistry(mcp, mode=tool_mode)

        registry.set_current_plugin("core", "CE")
        registry.capture_tool_metadata()

        _src_dir = _project_root / "src"
        plugin_results = load_all_plugins(
            mcp,
            settings,
            plugin_dirs=[
                _src_dir,
                _project_root / "plugins",
                _project_root / "private_plugins",
            ],
            context={"dynamic_registry": registry},
        )

        registry.set_current_plugin("gateway", "CE")
        registry.capture_tool_metadata()
        registry.finalize()

        loaded = sum(1 for r in plugin_results.values() if r.get("loaded"))
        logger.info("Standalone bootstrap: %d plugins, %d tools", loaded, registry.total_count)
        return registry

    except Exception as exc:
        logger.error("Standalone bootstrap failed: %s", exc)
        raise SystemExit(1) from exc


def main():
    parser = argparse.ArgumentParser(description="DataBridge Graph API Gateway")
    parser.add_argument("--host", default="0.0.0.0", help="Bind address (default: 0.0.0.0)")
    parser.add_argument("--port", type=int, default=8090, help="Port (default: 8090)")
    parser.add_argument("--reload", action="store_true", help="Enable auto-reload for development")
    args = parser.parse_args()

    print(f"\n{'='*60}")
    print("DataBridge Graph API Gateway v0.43.0")
    print(f"{'='*60}")

    dynamic_registry, tenant_registry = _bootstrap_registries()

    from databridge_mcp_gateway.app import create_app
    import uvicorn

    app = create_app(dynamic_registry, tenant_registry)

    print(f"\nGateway ready on http://{args.host}:{args.port}")
    print(f"  REST:    http://{args.host}:{args.port}/v1/{{module}}/{{tool}}")
    print(f"  MCP:     http://{args.host}:{args.port}/mcp")
    print(f"  WS:      ws://{args.host}:{args.port}/ws")
    print(f"  SSE:     http://{args.host}:{args.port}/mcp/sse")
    print(f"  Docs:    http://{args.host}:{args.port}/docs")
    print(f"  Health:  http://{args.host}:{args.port}/health")
    print(f"{'='*60}\n")

    uvicorn.run(app, host=args.host, port=args.port, reload=args.reload)


if __name__ == "__main__":
    main()
