from fastapi import APIRouter, HTTPException, Depends, Query, Request, Header
import os
import json
from urllib.parse import urlparse
from typing import Dict, Any
from dotenv import load_dotenv
from fastapi import APIRouter, Request, Header, HTTPException, Depends
from sqlalchemy.orm import Session
from src.utils.db import get_db, SessionLocal
from src.utils.settings import settings
from src.utils.models import Datasource
from src.utils.celery_worker import process_bright_review_data  # Import Celery task
import pusher

load_dotenv()

router = APIRouter()
bright_data_router = APIRouter()

# ------ WEBHOOK FOR THE ACTUAL BRIGHT DATA API WITH A STATIC TOKEN ------


# Load Bearer Token from Environment (with a fallback)
WEBHOOK_TOKEN = os.getenv("WEBHOOK_STATIC_TOKEN")

# Fetch environment variables
app_id = settings.app_id
key = settings.key
secret = settings.secret
cluster = settings.cluster
batch_size = settings.batch_size

# 1. Configure your Pusher credentials 
pusher_client = pusher.Pusher(
    app_id= app_id,  
    key=key,
    secret=secret,
    cluster=cluster,
    ssl=True
)

# Define a proper file path inside the assets folder
#TEMP_DIR = os.path.abspath("src/assets")  
#TEMP_FILE = os.path.join(TEMP_DIR, "bright_data_response.json")  # Store response here

@bright_data_router.post("/webhook")
async def bright_data_api_webhook(
    request_body: Request, 
    authorization: str = Header(None)
):
    """
    Webhook to receive review data from Bright Data API.
    - Verifies Bearer Token.
    - Sends data to Celery for processing.
    - Sends Pusher notification on failure.
    """
    # Validate Bearer Token
    if not authorization or not authorization.startswith("Bearer "):
        raise HTTPException(status_code=403, detail="Missing Bearer Token")
    
    token_parts = authorization.split(" ")
    if len(token_parts) < 2 or token_parts[1] != WEBHOOK_TOKEN:
        raise HTTPException(status_code=403, detail="Invalid Bearer Token")
    
    try:
        bright_data = await request_body.json()
        print(f"[Webhook Received Data]: {bright_data}")

        # 🚀 Send to Celery for async processing
        process_bright_review_data.delay(bright_data)

        return {"message": "Data received and sent to Celery for processing"}

    except Exception as e:
        print(f"[Webhook Error] {str(e)}")

        # 🔔 Send failure status to Pusher
        try:
            datasource_id = bright_data.get("datasource_id", "unknown")

            pusher_client.trigger(
                f"import-update",
                event_name="progress-update",
                data={
                    "processed": 0,
                    "total": 0,
                    "percent": 0,
                    "status": "failed",
                    "status_msg": "Webhook failed"
                }
            )
        except Exception as pusher_err:
            print(f"[Pusher Error in Webhook Failure Notification] {str(pusher_err)}")

        raise HTTPException(status_code=500, detail={"error": str(e)})




@bright_data_router.post("/notify")
async def bright_data_notify(request: Request):
    """
    Webhook to receive Bright Data API notifications (success or failure) and forward them via Pusher.
    """
    try:
        payload = await request.json()

        print("\n📩 Received Notification from Bright Data:")
        print(json.dumps(payload, indent=2))

        snapshot_id = payload.get("snapshot_id", "")
        status = payload.get("status", "").lower()
        error_msg = payload.get("error", "")
        error_codes = payload.get("error_codes", {})

        # Determine if it's a failure
        is_failure = bool(error_msg or error_codes)

        # Set frontend status accordingly
        if is_failure:
            frontend_status = "failed"
            frontend_status_msg = error_msg or "Bright Data API failed"
        elif status in ["ready", "done"]:
            frontend_status = "success"
            frontend_status_msg = "Bright Data API fetched successfully"
        else:
            print("⚠️ Notification status is unknown or not actionable.")
            return {"message": f"Status '{status}' ignored."}

        # 🔔 Send notification to frontend via Pusher
        pusher_client.trigger(
            "import-update",
            event_name="progress-update",
            data={
                "snapshot_id": snapshot_id,
                "processed": 0,
                "total": 0,
                "percent": 0,
                "status": frontend_status,
                "status_msg": frontend_status_msg
            }
        )

        return {"message": f"Pusher notification sent: {frontend_status}"}

    except Exception as e:
        print(f"❌ Error in notify webhook: {str(e)}")
        raise HTTPException(status_code=500, detail="Failed to process Bright Data notification")


