from fastapi import APIRouter, HTTPException, BackgroundTasks, Request,Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from .schema import ChatRequest, ChatResponse, PersistAI
from ..logger import log
from ..ChatAgent.chathandler import chat_with_ai, _persist_ai_response
from ..config import Config
import jwt

router = APIRouter()
security = HTTPBearer()


@router.post("/persist-ai-response")
async def persist_ai_response(request: PersistAI, background_tasks: BackgroundTasks):
    background_tasks.add_task(_persist_ai_response, request)
    return {"status": "success"}


@router.post("/chat", response_model=ChatResponse)
async def chat_endpoint(request: ChatRequest, credentials: HTTPAuthorizationCredentials = Depends(security),):
    try:
        token = credentials.credentials
        if not token:
            raise HTTPException(status_code=401, detail="Missing token")
        payload = jwt.decode(token, Config.JWT_SECRET,algorithms=["HS256"])

        user_id = payload.get("_id")
        if not user_id:
            log.error("user_id not found in token")
            raise HTTPException(status_code=401, detail="Invalid token")

        log.info(f"Authenticated user: {user_id}")

        response = await chat_with_ai(request, user_id=user_id)
        return response

    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Token expired")

    except jwt.InvalidTokenError:
        raise HTTPException(status_code=401, detail="Invalid token")

    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

    except Exception:
        log.exception("Unexpected error in chat endpoint")
        raise HTTPException(status_code=500, detail="Internal server error")