from fastapi import APIRouter, HTTPException, Depends, Query
from pydantic import BaseModel
from typing import Dict, Any, Optional
from sqlalchemy.orm import Session
from src.utils.db import get_db
from src.apps.users.models import User
from src.utils.settings import settings
from src.apps.auth.controller import get_current_user
from src.utils.celery_worker import process_csv_review_data  # Import Celery task
from typing import List
from src.apps.feedback.schemas import FeedbackResponse, TaskResponse
from src.apps.feedback.controller import fetch_sentiment_counts, fetch_sentiment_breakdown, fetch_review_count,fetch_feedback_rating, fetch_sentiment_score
import pusher

router = APIRouter()
feedback_router = APIRouter()

# 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
)

# ------ WEBHOOK API TO ACCEPT CSV FEEDBACK DATA AND SEND TO CELERY --------
class WebhookPayload(BaseModel):
    store_id: int
    branch_id: int
    datasource_id: int
    source_type: str
    snapshot_id: str
    reviews: list

@router.post("/webhook")
async def receive_data(payload: WebhookPayload):
    """
    Webhook that receives data and sends it to Celery for processing.
    Sends a Pusher notification on failure.
    """
    try:
        # Send data to Celery worker
        process_csv_review_data.delay(payload.dict())

        return {
            "message": "Data received and processing started",
            "snapshot_id": payload.snapshot_id
        }

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

        # 🔔 Send failure status to Pusher
        try:
            pusher_client.trigger(
                "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=str(e))



# ------ API ENDPOUNT TO GET SENTIMENT COUNT BY DATE -------
@feedback_router.get("/sentiment_counts", response_model=Dict[str, Any])
def get_sentiment_counts_results(
    branch_id: int,
    source: Optional[str] = Query(None, description="Filter by feedback source"),
    start_date: Optional[str] = Query(None, description="Start date in YYYY-MM-DD format"),
    end_date: Optional[str] = Query(None, description="End date in YYYY-MM-DD format"),
    min_rating: Optional[int] = None, 
    max_rating: Optional[int] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    API route to fetch sentiment counts (Protected).
    - Ensures the branch belongs to the logged-in user.
    - Allows filtering by source and date range.
    """
    return fetch_sentiment_counts(branch_id, db, current_user, source, start_date, end_date,min_rating, max_rating)



# ------ API ENDPOUNT TO GET SENTIMENT BREAKDOWN -------
@feedback_router.get("/sentiment_breakdown", response_model=Dict[str, Any])
def get_sentiment_breakdown_results(
    branch_id: int,
    source: Optional[str] = Query(None, description="Filter by feedback source"),
    start_date: Optional[str] = Query(None, description="Start date in YYYY-MM-DD format"),
    end_date: Optional[str] = Query(None, description="End date in YYYY-MM-DD format"),
    min_rating: Optional[int] = None, 
    max_rating: Optional[int] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    API route to fetch sentiment breakdown (Protected).
    - Ensures the branch belongs to the logged-in user.
    - Allows filtering by source and date range.
    """
    return fetch_sentiment_breakdown(branch_id, db, current_user, source, start_date, end_date,min_rating, max_rating)


# ------ API ENDPOUNT TO GET REVIEW COUNT BY DATE -------
@feedback_router.get("/review_count", response_model=Dict[str, Any])
def get_review_count_results(
    branch_id: int,
    source: Optional[str] = Query(None, description="Filter by feedback source"),
    start_date: Optional[str] = Query(None, description="Start date in YYYY-MM-DD format"),
    end_date: Optional[str] = Query(None, description="End date in YYYY-MM-DD format"),
    min_rating: Optional[int] = None, 
    max_rating: Optional[int] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    API route to fetch review count results (Protected).
    - Ensures the branch belongs to the logged-in user.
    - Allows filtering by source and date range.
    """
    return fetch_review_count(branch_id, db, current_user, source, start_date, end_date,min_rating, max_rating)

# ------ API ENDPOUNT TO GET RATING COUNT BY DATE -------
@feedback_router.get("/rating_count", response_model=Dict[str, Any])
def get_rating_count_results(
    branch_id: int,
    source: Optional[str] = Query(None, description="Filter by feedback source"),
    start_date: Optional[str] = Query(None, description="Start date in YYYY-MM-DD format"),
    end_date: Optional[str] = Query(None, description="End date in YYYY-MM-DD format"),
    min_rating: Optional[int] = None, 
    max_rating: Optional[int] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    API route to fetch sentiment analysis results (Protected).
    - Ensures the branch belongs to the logged-in user.
    - Allows filtering by source and date range.
    """
    return fetch_feedback_rating(branch_id, db, current_user, source, start_date, end_date,min_rating, max_rating)


#   ----------- API ENDPOINT TO GET SENTIMENT SCORE ------------
@feedback_router.get("/sentiment_score", response_model=Dict[str, Any])
def get_sentiment_score(
    branch_id: int,
    source: Optional[str] = Query(None, description="Filter by feedback source"),
    start_date: Optional[str] = Query(None, description="Start date in YYYY-MM-DD format"),
    end_date: Optional[str] = Query(None, description="End date in YYYY-MM-DD format"),
    min_rating: Optional[int] = None, 
    max_rating: Optional[int] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    API route to fetch sentiment score (Protected).
    - Ensures the branch belongs to the logged-in user.
    - Allows filtering by source and date range.
    """
    return fetch_sentiment_score(branch_id, db, current_user, source, start_date, end_date, min_rating, max_rating)




'''
@feedback_router.get("/tasks", response_model=Dict[str, Any])
def get_celery_task_results(
    branch_id: int, 
    datasource_id: int, 
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    API route to fetch Celery task results (Protected).
    - Ensures the branch belongs to the logged-in user.
    """
    return fetch_tasks(branch_id, datasource_id, db, current_user)  # Pass `current_user`




'''
