
import logging

from fastapi import (
    APIRouter,
    UploadFile,
    File,
    Response,
    Header,
    HTTPException,
    Depends
)

from fastapi.security import (
    HTTPBearer,
    HTTPAuthorizationCredentials
)

from fastapi.concurrency import run_in_threadpool

from app.utils.jwt import verify_access_token

from app.modules.enhanceImage.service import (
    enhance_image_service
)

from app.modules.device_limit.device_limit_repository import (
    DeviceLimitRepository
)

from app.modules.user_subscription.user_subscription_service import (
    UserSubscriptionService
)

router = APIRouter()

logger = logging.getLogger(__name__)

security = HTTPBearer(auto_error=False)

limit_repo = DeviceLimitRepository()

subscription_service = UserSubscriptionService()


@router.post("/enhance-4k")
async def enhance_image(

    file: UploadFile = File(...),

    device_id: str = Header(
        ...,
        alias="X-Device-Id"
    ),

    credentials: HTTPAuthorizationCredentials = Depends(
        security
    )

):

    import time

    start = time.perf_counter()

    premium_user = False


    # Premium Check
    if credentials:

        token = credentials.credentials

        payload = verify_access_token(token)

        if payload:

            premium_user = await subscription_service.has_active_subscription(
                payload["_id"]
            )


    # Daily Limit
    usage_info = None

    if not premium_user:

        usage_info = await limit_repo.check_and_increment_limit(
            device_id
        )

        if not usage_info["allowed"]:

            raise HTTPException(

                status_code=403,

                detail={

                    "success": False,
                    
                    "show_reward_ad":True,

                    "message": "Daily free limit reached. Watch ad to continue.",
                    
                    "free_count": usage_info["free_count"],
                    
                    "reward": usage_info["reward"],
                    
                    "adCount": usage_info["adCount"],
                    
                    "remaining_free": usage_info["remaining_free"]

                }

            )

    # Read Image
    image_bytes = await file.read()


    # AI Processing
    enhanced = await run_in_threadpool(

        enhance_image_service,

        image_bytes

    )

    total = round(

        time.perf_counter() - start,

        2

    )

    logger.info(
        f"Enhancement Completed in {total} sec"
    )
    
    headers = {}
    
    if usage_info:
        
        headers["X-Free-Count"] = str(
             usage_info["free_count"]
        )
        
        headers["X-Reward"] = str(
            usage_info["reward"]
        )
        
        headers["X-Ad-Count"] = str(
            usage_info["adCount"]
        )
        
        headers["X-Remaining-Free"] = str(
            usage_info["remaining_free"]
        )
        
        headers["X-Usage-Type"] = usage_info["source"]
        
    else: 
        
        headers["X-Usage-Type"] = "premium"

    return Response(

        content=enhanced,

        media_type="image/png",
        
        headers=headers

    )