from ninja import NinjaAPI
from django.core.cache import cache
from django.http import HttpRequest
from submissions.api import router as submissions_router
from submissions.schemas import UserInfoOut
from animations.api import router as results_router
from noita.api import router as noita_router
from games.api import router as games_router
from market.api import router as market_router

# Create the main API instance
api = NinjaAPI(
    title="PolyLAN Submission API",
    version="1.0.0",
    description="""API for managing Opus Magnum puzzle submissions, and Noita runs.

The Opus Magnum Submission API allows clients to upload, manage, validate, and review puzzle solution submissions for the Opus Magnum puzzle game community.
It provides features for user authentication, puzzle listing, submission uploads, automated and manual OCR validation, and administrative workflows.

The Noita Submission API allows clients to upload the result of the log file of the PolyLAN noita mod. It parses the output, and store each objectiv made by the user.
    """,
    openapi_extra={
        "info": {
            "contact": {
                "name": "Legrems",
                "email": "loic.gremaud@polylan.ch",
            },
        }
    },
)

# Add authentication for protected endpoints
# api.auth = django_auth  # Uncomment if you want global auth

# Include the submissions router
api.add_router("/submissions/", submissions_router, tags=["submissions"])
api.add_router("/results/", results_router, tags=["results"])
api.add_router("/noita/", noita_router, tags=["noita"])
api.add_router("/games/", games_router, tags=["games"])
api.add_router("/market/", market_router)


# Health check endpoint
@api.get("/health")
def health_check(request):
    """Health check endpoint"""
    return {"status": "healthy", "service": "polylan-submitter-api"}


# Cache management endpoint
@api.post("/cache/clear")
def clear_cache(request: HttpRequest):
    """Clear all API caches (admin only)"""
    if not request.user.is_authenticated or not request.user.is_staff:
        return 403, {"detail": "Admin access required"}

    keys = cache.keys("api:*")
    cache.delete_many(keys)

    return {"detail": f"Cleared {len(keys)} cache entries"}


# User info endpoint
@api.get("/user", response=UserInfoOut)
def get_user_info(request):
    """Get current user information"""
    user = request.user

    if user.is_authenticated:
        return {
            "id": user.id,
            "username": user.username,
            "first_name": user.first_name,
            "last_name": user.last_name,
            "email": user.email,
            "is_authenticated": True,
            "is_staff": user.is_staff,
            "is_superuser": user.is_superuser,
            "cas_groups": getattr(user, "cas_groups", []),
        }
    else:
        return {
            "is_authenticated": False,
            "is_staff": False,
            "is_superuser": False,
        }
