# saas/api/v2/surveys.py
"""
API endpoints for instant surveys.
Auto-triggers after Salesforce connection.
"""

from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from datetime import datetime

from ...db import get_session
from ...auth import get_current_account
from ...models import Integration, IntegrationProvider
from ...services.salesforce_gateway import SalesforceGateway
from ...services.instant_survey import InstantSurvey
from ...services.survey_results_service import SurveyResultsService

# from ...services.sse_manager import sse_manager  # TODO: Implement SSE manager
sse_manager = None  # Placeholder for now

router = APIRouter(prefix="/api/v2/surveys", tags=["surveys"])


@router.post("/instant")
async def run_instant_survey(
    background_tasks: BackgroundTasks,
    db: AsyncSession = Depends(get_session),
    account_id: str = Depends(get_current_account),
):
    """
    Run instant survey on connected Salesforce.
    Returns immediately with survey_id, runs in background.
    """
    # Get Salesforce integration
    result = await db.execute(
        select(Integration).where(
            Integration.account_id == str(account_id),
            Integration.provider == IntegrationProvider.SALESFORCE,
            Integration.is_active == True,
        )
    )
    integration = result.scalar_one_or_none()

    if not integration:
        raise HTTPException(400, "Salesforce not connected")

    # Create survey ID
    survey_id = f"survey_{account_id}_{datetime.utcnow().timestamp()}"

    # Launch background task
    background_tasks.add_task(
        _run_survey_background, db, integration, survey_id, account_id
    )

    return {
        "survey_id": survey_id,
        "status": "started",
        "message": "Survey started, listen to SSE for progress",
    }


@router.get("/instant/{survey_id}")
async def get_survey_status(
    survey_id: str,
    db: AsyncSession = Depends(get_session),
    account_id: str = Depends(get_current_account),
):
    """Get survey results if complete."""
    # Check cache/storage for results
    # For MVP, you might store in Redis or a simple table
    # This is a placeholder
    return {
        "survey_id": survey_id,
        "status": "running",
        "message": "Survey in progress",
    }


async def _run_survey_background(
    db: AsyncSession, integration: Integration, survey_id: str, account_id: str
):
    """Background task to run survey."""
    try:
        # Create SF gateway
        sf_client = await SalesforceGateway.for_tenant(integration.account_id, db)

        # Progress callback via SSE
        def progress_callback(data):
            if sse_manager:
                sse_manager.send_event(
                    account_id,
                    {"type": "survey_progress", "survey_id": survey_id, **data},
                )

        # Run survey
        survey = InstantSurvey(sf_client, progress_callback)
        results = await survey.run()

        # Store results using SurveyResultsService
        results_service = SurveyResultsService(db)
        await results_service.store_results(
            survey_id=survey_id,
            account_id=account_id,
            integration_id=str(integration.id),
            results=results,
        )

        # Send completion event
        if sse_manager:
            sse_manager.send_event(
                account_id,
                {
                    "type": "survey_complete",
                    "survey_id": survey_id,
                    "summary": results.get("summary", {}),
                },
            )

    except Exception as e:
        # Send error event
        if sse_manager:
            sse_manager.send_event(
                account_id,
                {"type": "survey_error", "survey_id": survey_id, "error": str(e)},
            )
        import logging

        logging.getLogger(__name__).error(
            f"Survey background task failed: {e}", exc_info=True
        )


async def _store_survey_results(survey_id: str, results: dict):
    """Store survey results for retrieval."""
    # For MVP, could use Redis with TTL
    # Or create a SurveyResult table
    # This is a placeholder
    pass


# Auto-trigger endpoint (called after OAuth success)
@router.post("/trigger-after-oauth")
async def trigger_survey_after_oauth(
    integration_id: str,
    background_tasks: BackgroundTasks,
    db: AsyncSession = Depends(get_session),
):
    """
    Called internally after successful OAuth.
    Triggers instant survey automatically.
    """
    result = await db.execute(
        select(Integration).where(Integration.id == integration_id)
    )
    integration = result.scalar_one_or_none()

    if not integration:
        return {"error": "Integration not found"}

    survey_id = f"survey_{integration.account_id}_{datetime.utcnow().timestamp()}"

    background_tasks.add_task(
        _run_survey_background, db, integration, survey_id, integration.account_id
    )

    return {"survey_id": survey_id, "triggered": True}
