import os
import time
import jwt
from fastapi import HTTPException
from app.core.config import settings

def encode_jwt_token(user):
    print(f"Encoding JWT token for user_device: {user}")  # Debug log
    """
    Encode JWT with user_device payload.
    Expects JWT_KEY and JWT_EXPIRE_CLAIM in environment variables.
    """
    try:
        if not user:
            raise HTTPException(status_code=404, detail="Device not found")

        secret = settings.JWT_SECRET
        expire_seconds = settings.JWT_EXPIRE_MINUTES
        if not secret:
            return {"code":401, "message":"JWT_KEY is not configured"}
            # raise HTTPException(status_code=500, detail="JWT_KEY is not configured")

        data = {
            "exp": int(time.time()) + expire_seconds,
            "data": {
                "user_id": user["user_id"],
                "signup_type": user["signup_type"],
                "social_id": user["social_id"],
                "firstname": user["firstname"],
                "lastname": user["lastname"],
                "fullname": user["fullname"],
                "email": user["email"],
                "profilepic": user.get("profilepic") or "",
                "is_profile_completed": user["is_profile_completed"],
                "is_new_user": user["is_new_user"],
                "user_device_id": user["user_device_id"],
                "device_unique_id": user["device_unique_id"],
                "device_name": user["device_name"],
                "device_token": user["device_token"],
                "device_type": user["device_type"],
                "app_version": user["app_version"],
                "have_active_subscription": user.get("have_active_subscription") or False,
                "subscription": user.get("subscription") or None,
                "auth_key": user['auth_key'] if 'auth_key' in user else None
            }
        }

        token = jwt.encode(data, secret, algorithm="HS256")
        
        # print(f"JWT token generated successfully: {token}")  # Debug log
        return token
    except HTTPException:
        return {"code":500, "message":"Internal server error: JWT encoding failed"}
    except Exception as e:
        return {"code":500, "message":f"Internal server error: {str(e)}"}
        raise HTTPException(status_code=500, detail=f"Error encoding JWT: {e}")
