"""
CertiChain Python Service — FastAPI
Point d'entrée de l'application.

Endpoints exposés :
  POST /blockchain/emit                    — Émettre un diplôme sur la blockchain
  POST /blockchain/verify/{hash}           — Vérifier un diplôme (lecture seule)
  POST /blockchain/revoke/{hash}           — Révoquer un diplôme
  POST /blockchain/university/register     — Enregistrer une université
  GET  /blockchain/hash                    — Calculer un hash (sans transaction)
  POST /ai/detect-fraud                    — Analyser une image de diplôme
  GET  /health                             — Health check (utilisé par Laravel)
"""
import logging
import secrets

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from app.config import settings
from app.routers import blockchain, fraud
from app.services.blockchain_service import blockchain_service

logging.basicConfig(
    level=logging.DEBUG if settings.debug else logging.INFO,
    format="%(asctime)s | %(levelname)-8s | %(name)s : %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)

app = FastAPI(
    title="CertiChain Python Service",
    description="Microservice FastAPI — Blockchain Polygon + Détection de fraude IA",
    version="1.0.0",
    docs_url="/docs" if settings.debug else None,
    redoc_url="/redoc" if settings.debug else None,
)


# Authentification par clé partagée — le service est joignable publiquement en production
@app.middleware("http")
async def require_service_key(request: Request, call_next):
    if settings.service_api_key and not request.url.path.endswith("/health"):
        provided = request.headers.get("x-service-key", "")
        if not secrets.compare_digest(provided, settings.service_api_key):
            return JSONResponse(status_code=401, content={"detail": "Unauthorized"})
    return await call_next(request)

# CORS — uniquement pour l'app Laravel en local / prod
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost", "http://127.0.0.1", "http://localhost:8000"],
    allow_methods=["GET", "POST"],
    allow_headers=["*"],
)

# Routers
app.include_router(blockchain.router)
app.include_router(fraud.router)


@app.get("/health", tags=["health"], summary="Health check")
async def health() -> dict:
    """
    Vérifie l'état du service.
    Appelé par Laravel (PythonBridgeService::isAvailable()) pour savoir si le service est opérationnel.
    """
    blockchain_ok = blockchain_service.is_available()
    return {
        "status":     "ok",
        "service":    "certichain-python",
        "blockchain": "connected" if blockchain_ok else "not_configured",
    }
