import logging
from fastapi import FastAPI, Request, HTTPException, status
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse, StreamingResponse
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from src.db.session import get_db
from src.utils.response_utils import create_response
from src.utils.logger import log_error, log_operation
from src.api.v1.endpoints import role, permission, user, page
from src.db.models.operation_type_enum import OperationTypeEnum

# Configure basic logging
logging.basicConfig(level=logging.DEBUG)

# FastAPI app initialization
# app = FastAPI(debug=True)
# app.root_path="/api" 
app = FastAPI(debug=True, root_path="/api")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://junceraautomations.com", "https://www.junceraautomations.com","http://localhost:4200"],  # Allow both production and local dev
    allow_credentials=True,
    allow_methods=["*"],  # Or specify only the methods you need, e.g., ["GET", "POST"]
    allow_headers=["*"],  # Or specify the allowed headers
)
 
# Custom exception handlers
@app.exception_handler(HTTPException)
async def custom_http_exception_handler(request: Request, exc: HTTPException):
    db: Session = next(get_db())
    log_error(db, str(exc.detail), path=str(request.url), method=request.method)
    logging.error(f"HTTP Exception: {exc.detail} for request {request.url}")
    return JSONResponse(
        status_code=exc.status_code,
        content=create_response(error=exc.detail)
    )

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    db: Session = next(get_db())
    log_error(db, str(exc), path=str(request.url), method=request.method)
    logging.error(f"Validation error: {exc} for request {request.url}")
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content=create_response(error="Validation error")
    )

@app.middleware("http")
async def log_operations(request: Request, call_next):
    logging.debug(f"Incoming request: {request.method} {request.url}")
    db: Session = next(get_db())
    
    try:
        response = await call_next(request)
        logging.debug(f"Response status: {response.status_code} for {request.url}")

        if request.method in ("POST", "PUT", "DELETE"):
            path_parts = request.url.path.split("/")
            model_name = path_parts[3] if len(path_parts) > 3 else None
            operation_type = (
                OperationTypeEnum.CREATE if request.method == "POST"
                else OperationTypeEnum.UPDATE if request.method == "PUT"
                else OperationTypeEnum.DELETE if request.method == "DELETE"
                else None
            )
            if model_name and operation_type:
                log_operation(db, model_name, operation_type, description=f"{request.method} operation performed.")

        # Handle JSONResponse
        if isinstance(response, JSONResponse):
            logging.debug(f"JSON Response: {response.body.decode('utf-8')}")
            return response

        # Handle StreamingResponse
        elif isinstance(response, StreamingResponse):
            logging.debug(f"Streaming Response: {response}")
            return response

        # Handle other response types by reading content
        else:
            try:
                original_content = await response.read()  # Use read() to get response content
                logging.debug(f"Other Response: {original_content.decode('utf-8')}")
            except Exception as e:
                logging.error(f"Error processing response: {e}")
                original_content = None

            return response

    except IntegrityError as exc:
        log_error(db, str(exc.orig), path=str(request.url), method=request.method)
        logging.error(f"Integrity Error: {exc.orig}")
        return JSONResponse(
            status_code=status.HTTP_400_BAD_REQUEST,
            content=create_response(error=str(exc.orig))
        )
    except Exception as exc:
        log_error(db, str(exc), path=str(request.url), method=request.method)
        logging.error(f"Unexpected Error: {exc}")
        return JSONResponse(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            content=create_response(error=str(exc))
        )




 
# Registering the routers
app.mount("/api/uploads/images", StaticFiles(directory="uploads/images"), name="images")
app.include_router(user.router, prefix="/users", tags=["users"])
app.include_router(role.router, prefix="/roles", tags=["roles"])
app.include_router(permission.router, prefix="/permissions", tags=["permissions"])
app.include_router(page.router, prefix="/page", tags=["Pages"])

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000,)