"""
FastAPI app instance for Gateway Bot
"""
import logging
import os
import sys
from pathlib import Path

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from http_api import router as gateway_router
from http_api_doc import router as doc_router

import gateway_boot

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

app = FastAPI(
    title="Bot Gateway with DAARWIZZ",
    version="1.0.0",
    description="Gateway service for Telegram/Discord bots → DAGI Router"
)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include gateway routes
app.include_router(gateway_router, prefix="", tags=["gateway"])
app.include_router(doc_router, prefix="", tags=["docs"])


@app.on_event("startup")
async def startup_stepan_check():
    """Check crews + agromatrix_tools availability. Do not crash gateway if missing."""
    # Шляхи для inproc: gateway volume (основний) або repo root (dev)
    gw_dir = str(Path(__file__).parent)  # /app/gateway-bot
    repo_root = os.getenv("AGX_REPO_ROOT", "/opt/microdao-daarion").strip()
    candidate_paths = [
        gw_dir,                                            # /app/gateway-bot (crews/ тут)
        str(Path(gw_dir) / "agromatrix-tools"),            # /app/gateway-bot/agromatrix-tools
        repo_root,                                         # /opt/microdao-daarion
        str(Path(repo_root) / "packages" / "agromatrix-tools"),
        str(Path(repo_root) / "packages" / "agromatrix-tools" / "agromatrix_tools"),
    ]
    for p in candidate_paths:
        if p and p not in sys.path:
            sys.path.insert(0, p)
    try:
        import crews.agromatrix_crew.run  # noqa: F401
        import agromatrix_tools  # noqa: F401
        gateway_boot.STEPAN_IMPORTS_OK = True
        logger.info("Stepan inproc: crews + agromatrix_tools OK; STEPAN_IMPORTS_OK=True")
    except Exception as e:
        logger.error(
            "Stepan disabled: crews or agromatrix_tools not available: %s. "
            "Set AGX_REPO_ROOT, mount crews and packages/agromatrix-tools.",
            e,
        )
        gateway_boot.STEPAN_IMPORTS_OK = False


@app.get("/")
async def root():
    return {
        "service": "bot-gateway",
        "version": "1.0.0",
        "agent": "DAARWIZZ",
        "endpoints": [
            "POST /telegram/webhook",
            "POST /discord/webhook",
            "POST /api/doc/parse",
            "POST /api/doc/ingest",
            "POST /api/doc/ask",
            "GET /api/doc/context/{session_id}",
            "GET /health"
        ]
    }
