import os
import json
import random
import inspect
from typing import Annotated, Dict, List, Optional
from contextlib import contextmanager

from app.routers.auth import get_supabase, router as auth_router
from fastapi import FastAPI, Depends, HTTPException, status, Request
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel, EmailStr, field_validator, ValidationInfo, Field, SecretStr
from pydantic_core.core_schema import FieldValidationInfo

from dotenv import load_dotenv
from supabase import Client
from uuid import uuid4
from datetime import datetime

# Initialize FastAPI app
app = FastAPI(title="XTablo API")

# CORS Middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["X-Error-Code", "X-Error-Message"]
)

app.include_router(auth_router, prefix="/auth")

# Security
security = HTTPBearer()

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    errors = exc.errors()

    custom_errors = []
    for error in errors:
        custom_message = error["msg"]
        if custom_message.startswith("Value error, "):
            custom_message = custom_message.split(", ")[1]

        custom_errors.append({
            **error,
            "form_location": error["loc"][-1],
            "human_error": custom_message
        })
        
    return JSONResponse(status_code=422, content=jsonable_encoder(custom_errors))
    


@app.get("/ping")
async def ping():
    """Health check endpoint that returns a success status."""
    return {"status": "success", "message": "API is running"}
