from fastapi import HTTPException, Request, Depends
from fastapi.responses import JSONResponse
from sqlalchemy.future import select
from sqlalchemy.ext.asyncio import AsyncSession
import jwt
import os

from app.db.session import get_db
from app.models.user_device import UserDevice
from app.models.user import User

from app.core.config import settings
from app.utils.responses import custom_response

# This check is now redundant since the secret is loaded via Pydantic settings.
# The Settings class handles validation at startup.
# if not secret:
#     raise HTTPException(status_code=500, detail="JWT_KEY is not configured")

async def validate_token(request: Request, db: AsyncSession = Depends(get_db)):
    """
    Asynchronously validates a JWT token and retrieves associated user data.
    """
    print(f"Validating token for request: {request}")  # Debug log
    auth_header = request.headers.get("Authorization")
    if not auth_header:
        # Use custom_response for consistent API format
        print("Authorization header missing")  # Debug log
        return {"code":401, "message":"Authorization header missing"}

    try:
        scheme, token = auth_header.split()
        if scheme.lower() != "bearer":
            return {"code":401, "message":"Authorization scheme must be Bearer"}

    except ValueError:
        return {"code":401, "message":"Invalid Authorization header format"}

    try:
        # ✅ NEW: Use the secret from your settings file
        decoded_token = jwt.decode(token, settings.JWT_SECRET, algorithms=["HS256"])
        print(f"[DEBUG] Decoded token: {decoded_token}")  # Debug log
        
        user_id = decoded_token.get("data", {}).get("user_id")
        user_device_id = decoded_token.get("data", {}).get("user_device_id")
        auth_key = decoded_token.get("data", {}).get("auth_key")
        print(f"[DEBUG] User ID: {user_id}, Device ID: {user_device_id}")  # Debug log
        if not user_device_id:
            return {"code":401, "message":"Unauthorized: Missing user_device_id"}
        
        # ✅ NEW: Use async query to check for device
        device_stmt = select(UserDevice).filter(UserDevice.user_device_id == user_device_id)
        device_result = await db.execute(device_stmt)
        device = device_result.scalars().first()

        if not device:
            return {"code":401, "message":"Unauthorized: User not found"}

        user = None
        if user_id:
            # ✅ NEW: Use async query to check for user
            user_stmt = select(User).filter(User.user_id == user_id,User.is_deleted == 0 )
            user_result = await db.execute(user_stmt)
            user = user_result.scalars().first()
            
            print('user-----------------------------=-====-=-=-', user_id)
            if not user:
                return {"code":401, "message":"Unauthorized: User not found"}
        print(f"[DEBUG] User found: {user_id}")  # Debug log


        # Return both values so API can use
        return {"code":200, "message":"User Found!","user_device_id": user_device_id, "user_id": user_id, "auth_token": auth_key, "device_type": device.device_type if device else None}

    except jwt.ExpiredSignatureError:
        return {"code":401, "message":"Token has expired"}
    
    except jwt.InvalidTokenError:
        return {"code":401, "message":"Invalid token"}

    except Exception as e:
        return {"code":401, "message":"Internal Server Error: {str(e)}"}
