import logging
from pathlib import Path

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager

from .routes import router

logger = logging.getLogger(__name__)
from .config import settings
from .dependencies import es_client, oracle_client, ranking_oracle_repo, get_processar_job
from ...application.jobs.scheduler import RankingScheduler


@asynccontextmanager
async def lifespan(app: FastAPI):
    await es_client.connect()

    try:
        if oracle_client:
            oracle_client.connect()
            if oracle_client.is_connected:
                total = ranking_oracle_repo.contar_total() if ranking_oracle_repo else 0
                logger.info(f"Conectado ao Oracle - {total} consultores no ranking")
            else:
                logger.warning("Não foi possível conectar ao Oracle")
    except Exception as e:
        logger.warning(f"Erro ao inicializar Oracle: {e}")

    scheduler = None
    try:
        if settings.SCHEDULER_ENABLED:
            job = get_processar_job()
            scheduler = RankingScheduler(job)
            await scheduler.iniciar(hora_alvo=settings.SCHEDULER_HOUR)
    except Exception as e:
        logger.warning(f"Scheduler não iniciou: {e}")

    yield

    if scheduler:
        try:
            scheduler.parar()
        except Exception:
            pass

    if oracle_client:
        try:
            oracle_client.close()
        except Exception:
            pass

    await es_client.close()


app = FastAPI(
    title="Ranking de Consultores CAPES",
    description="Sistema de Ranking de Consultores CAPES baseado na Minuta Técnica",
    version="1.0.0",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(router)

static_dir = Path(__file__).parent.parent.parent.parent / "static"
if static_dir.exists():
    app.mount("/api/static", StaticFiles(directory=str(static_dir)), name="static")


@app.get("/")
async def root():
    return {
        "message": "API Ranking CAPES",
        "version": "1.0.0",
        "docs": "/docs",
        "health": "/api/v1/health",
    }
