from typing import Annotated, Any, Optional
from uuid import UUID
from fastapi import APIRouter, Depends, Header, HTTPException, Request, status
from sqlalchemy.ext.asyncio import AsyncSession
from core.config import get_settings
from core.exceptions import NotFoundError, UnauthorizedError, ValidationError
from core.logging import get_logger
from infrastructure.database.session import get_db
from infrastructure.telegram.webhook import verify_webhook_secret
from modules.billing.service import BillingService
from modules.bots.service import BotService

logger = get_logger(__name__)

router = APIRouter(prefix="/webhooks", tags=["Webhook Ingestion"])


@router.post("/telegram/{bot_id}", status_code=status.HTTP_200_OK)
async def receive_telegram_webhook(
    bot_id: UUID,
    request: Request,
    db: Annotated[AsyncSession, Depends(get_db)],
    x_telegram_bot_api_secret_token: Annotated[Optional[str], Header()] = None,
):
    """
    Ingests and processes incoming Telegram Bot API updates.
    Validates X-Telegram-Bot-Api-Secret-Token before processing.
    """
    if not x_telegram_bot_api_secret_token:
        logger.warning("webhook_missing_secret_token", bot_id=str(bot_id))
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Missing X-Telegram-Bot-Api-Secret-Token header",
        )

    try:
        update_dict = await request.json()
    except Exception as exc:
        logger.error("webhook_invalid_json", bot_id=str(bot_id), error=str(exc))
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid JSON payload")

    service = BotService(db)

    # Check if async queue processing is desired (production or explicitly requested)
    settings = get_settings()
    is_async_requested = request.headers.get("X-Async-Processing", "").lower() == "true"
    is_sync_forced = request.headers.get("X-Sync-Processing", "").lower() == "true"
    should_queue = is_async_requested and not is_sync_forced

    if should_queue:
        # Pre-validate bot and secret token before accepting webhook
        bot = await service.repo.get_by_id(bot_id)
        if not bot or bot.status != "active":
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Bot is inactive or not found")

        webhook = await service.repo.get_webhook(bot_id)
        if not webhook or not webhook.is_active:
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Bot webhook is not active")

        if not verify_webhook_secret(x_telegram_bot_api_secret_token, webhook.secret_hash):
            logger.warning("webhook_secret_mismatch", bot_id=str(bot_id))
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid Telegram webhook secret token")

        try:
            import apps.worker.celery_app
            from apps.worker.tasks.telegram import process_telegram_update_task
            task = process_telegram_update_task.delay(
                str(bot_id),
                x_telegram_bot_api_secret_token,
                update_dict,
                str(bot.tenant_id),
            )
            return {"ok": True, "queued": True, "task_id": task.id}
        except Exception as queue_exc:
            logger.warning("celery_enqueue_fallback_to_sync", error=str(queue_exc), bot_id=str(bot_id))
            # Graceful fallback to inline synchronous execution if Celery broker is temporarily unreachable

    try:
        res = await service.handle_webhook_update(
            bot_id=bot_id,
            received_secret_token=x_telegram_bot_api_secret_token,
            update_dict=update_dict,
        )
        return res
    except UnauthorizedError as exc:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(exc.message))
    except NotFoundError as exc:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc.message))
    except Exception as exc:
        import traceback
        logger.error("webhook_processing_error", bot_id=str(bot_id), error=str(exc), traceback=traceback.format_exc())
        return {"ok": False, "error": str(exc)}


@router.post("/razorpay", status_code=status.HTTP_200_OK)
async def receive_razorpay_webhook(
    request: Request,
    db: Annotated[AsyncSession, Depends(get_db)],
    x_razorpay_signature: Annotated[Optional[str], Header()] = None,
    x_razorpay_event_id: Annotated[Optional[str], Header()] = None,
):
    """
    Ingests Razorpay webhook notifications.
    Verifies HMAC-SHA256 signature and guarantees duplicate event protection.
    """
    if not x_razorpay_signature:
        logger.warning("razorpay_webhook_missing_signature")
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing X-Razorpay-Signature header")

    payload_bytes = await request.body()
    service = BillingService(db)

    try:
        headers = {
            "x-razorpay-signature": x_razorpay_signature,
            "x-razorpay-event-id": x_razorpay_event_id or "",
        }
        res = await service.handle_webhook(
            provider="razorpay",
            payload_bytes=payload_bytes,
            signature=x_razorpay_signature,
            headers=headers,
        )
        return res
    except UnauthorizedError as exc:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(exc.message))
    except ValidationError as exc:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc.message))
    except Exception as exc:
        logger.error("razorpay_webhook_processing_error", error=str(exc))
        return {"status": "error", "error": str(exc)}


@router.post("/stripe", status_code=status.HTTP_200_OK)
async def receive_stripe_webhook(
    request: Request,
    db: Annotated[AsyncSession, Depends(get_db)],
    stripe_signature: Annotated[Optional[str], Header()] = None,
):
    """
    Ingests Stripe webhook events (checkout.session.completed, payment_intent, etc.).
    Verifies Stripe-Signature and enforces duplicate event idempotency.
    """
    if not stripe_signature:
        logger.warning("stripe_webhook_missing_signature")
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing Stripe-Signature header")

    payload_bytes = await request.body()
    service = BillingService(db)

    try:
        res = await service.handle_webhook(
            provider="stripe",
            payload_bytes=payload_bytes,
            signature=stripe_signature,
        )
        return res
    except UnauthorizedError as exc:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(exc.message))
    except ValidationError as exc:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc.message))
    except Exception as exc:
        logger.error("stripe_webhook_processing_error", error=str(exc))
        return {"status": "error", "error": str(exc)}
