import json
import logging
from django.http import JsonResponse, HttpResponse
from .services import FacebookService
from django.conf import settings

# Configure logging
logger = logging.getLogger(__name__)

PAGE_ACCESS_TOKEN = settings.PAGE_ACCESS_TOKEN

def verify_webhook_token(mode, token, challenge, verify_token):
    """
    Verifies the webhook token and mode.
    """
    if mode == "subscribe" and token == verify_token:
        logger.info("Webhook verified successfully.")
        return HttpResponse(challenge, status=200)
    else:
        logger.warning(f"Webhook verification failed. Mode: {mode}, Token: {token}")
        return HttpResponse("Forbidden", status=403)


def parse_webhook_payload(payload):
    """
    Parses the webhook payload and extracts relevant data.
    """
    try:
        entry = payload.get("entry", [{}])[0]
        changes = entry.get("changes", [{}])[0]
        value = changes.get("value", {})
        return value
    except Exception as e:
        logger.error(f"Error parsing payload: {e}")
        raise


def handle_comment_event(page_id, sender_id, data):
    """
    Handles incoming comment events.
    """
    if sender_id == page_id:
        logger.info(f"Skipping self-generated comment. Sender ID: {sender_id}, Page ID: {page_id}")
        return JsonResponse({"status": "skipped"}, status=200)

    comment_id = data.get("comment_id")
    original_message = data.get("message")

    if comment_id and original_message:
        fb_service = FacebookService(PAGE_ACCESS_TOKEN)
        fb_service.reply_to_comment(page_id, comment_id, original_message)
        logger.info(f"Successfully replied to comment ID: {comment_id} with bot response: {original_message}")

    return JsonResponse({"status": "comment_handled"}, status=200)


def handle_share_event(page_id, data):
    """
    Handles incoming share events.
    """
    share_link = data.get("link")
    post_id = data.get("post_id")
    share_id = data.get("share_id")
    original_message = data.get("message")

    logger.info(f"Post {post_id} was shared. Share ID: {share_id}, Link: {share_link}")

    fb_service = FacebookService(PAGE_ACCESS_TOKEN)
    fb_service.post_comment_on_share(page_id, post_id, original_message)

    return JsonResponse({"status": "share_logged"}, status=200)
