"""Top-up and usage API endpoints."""

from fastapi import APIRouter, Depends, HTTPException
from loguru import logger
from sqlmodel import Session

from app.auth import get_current_user
from app.database import get_session
from app.repositories.pricing import PricingRepository
from app.repositories.topup import TopupRepository
from app.schemas.auth import CurrentUser
from app.schemas.topup import (
    PlanInfo, RemainingInfo, TopupPlanOut,
    UsageResponse, VerifyTopupRequest, VerifyTopupResponse,
)
from app.services.google_play import get_android_publisher
from app.services.usage import UsageService

router = APIRouter()


@router.get("/topup-plans", response_model=list[TopupPlanOut])
async def list_topup_plans(session: Session = Depends(get_session)):
    """Return available top-up packs for the frontend to display."""
    plans = TopupRepository(session).get_active_plans()
    return [
        TopupPlanOut(
            topupPlanId=p.topup_plan_id,
            name=p.name,
            price=p.price,
            images=p.images,
            videos=p.videos,
            productId=p.product_id,
        )
        for p in plans
    ]


@router.post("/topup/verify", response_model=VerifyTopupResponse)
async def verify_topup(
    body: VerifyTopupRequest,
    current_user: CurrentUser = Depends(get_current_user),
    session: Session = Depends(get_session),
):
    """Verify a Google Play one-time purchase for a top-up pack and credit the user."""
    try:
        user_id = current_user.sub

        topup_repo = TopupRepository(session)

        plan = topup_repo.get_plan_by_product(body.productId)
        if not plan:
            raise HTTPException(status_code=400, detail=f"Unknown topup product: {body.productId}")

        if topup_repo.get_purchase_by_token(body.purchaseToken):
            return VerifyTopupResponse(status="already_credited", message="This purchase was already credited")

        order_id = ""
        publisher = get_android_publisher()
        if publisher:
            try:
                from app.config import GOOGLE_PLAY_PACKAGE_NAME
                result = publisher.purchases().products().get(
                    packageName=GOOGLE_PLAY_PACKAGE_NAME,
                    productId=body.productId,
                    token=body.purchaseToken,
                ).execute()
                purchase_state = result.get("purchaseState", -1)
                order_id = result.get("orderId", "")
                if purchase_state != 0:
                    raise HTTPException(status_code=400, detail="Purchase not completed")
                logger.info(f"TOPUP_GOOGLE_VERIFIED: order={order_id} product={body.productId}")
            except HTTPException:
                raise
            except Exception as e:
                logger.warning(f"Google Play verification failed, trusting client: {e}")

        topup_repo.create_purchase(
            user_id=user_id,
            topup_plan_id=plan.topup_plan_id,
            order_id=order_id,
            purchase_token=body.purchaseToken,
            images=plan.images,
            videos=plan.videos,
        )

        logger.info(
            f"TOPUP_CREDITED: user={user_id} plan={plan.topup_plan_id} "
            f"images={plan.images} videos={plan.videos} order={order_id}"
        )

        return VerifyTopupResponse(
            status="credited",
            topupPlanId=plan.topup_plan_id,
            imagesAdded=plan.images,
            videosAdded=plan.videos,
        )

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Topup verification failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/usage", response_model=UsageResponse)
async def get_usage(
    current_user: CurrentUser = Depends(get_current_user),
    session: Session = Depends(get_session),
):
    """Return current usage state for the frontend."""
    usage = UsageService(session).get_usage_state(current_user.sub)

    limits = PricingRepository(session).get_limits(usage["tier_id"])

    return UsageResponse(
        isPremium=usage["is_premium"],
        tier=usage["tier_id"],
        plan=PlanInfo(
            maxImages=limits.max_images if limits else 0,
            maxVideos=limits.max_videos if limits else 0,
            maxPpts=limits.max_ppts if limits else 0,
            windowHours=limits.window_hours if limits else 24,
        ),
        remaining=RemainingInfo(
            planImages=usage["plan_images_remaining"],
            planVideos=usage["plan_videos_remaining"],
            planPpts=usage["plan_ppts_remaining"],
            topupImages=usage["topup_images_remaining"],
            topupVideos=usage["topup_videos_remaining"],
            totalImages=usage["plan_images_remaining"] + usage["topup_images_remaining"],
            totalVideos=usage["plan_videos_remaining"] + usage["topup_videos_remaining"],
        ),
    )
