# Mock survey endpoint for frontend testing
"""
Mock survey endpoints for testing the frontend without Salesforce connection.
"""

from fastapi import APIRouter, BackgroundTasks
import asyncio
import random
from datetime import datetime

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

# Store for mock survey results
mock_survey_results = {}


@router.post("/mock")
async def run_mock_survey(background_tasks: BackgroundTasks):
    """
    Mock survey endpoint for testing frontend.
    Returns immediately with survey_id, simulates progress.
    """
    survey_id = f"survey_mock_{datetime.utcnow().timestamp()}"

    # Launch background task to simulate survey
    background_tasks.add_task(simulate_survey_progress, survey_id)

    return {
        "survey_id": survey_id,
        "status": "started",
        "message": "Mock survey started for testing",
    }


async def simulate_survey_progress(survey_id: str):
    """Simulate survey progress with delays."""
    # Wait a bit to simulate processing
    await asyncio.sleep(2)

    # Generate mock results
    results = {
        "survey_id": survey_id,
        "status": "complete",
        "summary": {
            "duplicates_found": random.randint(20, 100),
            "data_quality_score": random.randint(60, 95),
            "grade": random.choice(["A", "A-", "B+", "B", "B-", "C+"]),
            "enrichment_opportunities": random.randint(5, 30),
            "total_records_scanned": random.randint(1000, 10000),
            "objects_analyzed": ["Account", "Contact", "Lead"],
            "duplicate_examples": [
                {
                    "records": [
                        {"Name": "Acme Corp", "Id": "001xxx001"},
                        {"Name": "Acme Corporation", "Id": "001xxx002"},
                    ],
                    "score": 0.92,
                    "tier": "CERTAIN",
                    "explanation": "Strong name match with similar addresses",
                    "visual": "███████████████████░ 92%",
                    "contributions": {"Name": 0.45, "Address": 0.25, "Phone": 0.22},
                },
                {
                    "records": [
                        {"Name": "Tech Solutions Inc", "Id": "001xxx003"},
                        {"Name": "Tech Solutions", "Id": "001xxx004"},
                    ],
                    "score": 0.85,
                    "tier": "LIKELY",
                    "explanation": "Probable duplicate with name variation",
                    "visual": "█████████████████░░░ 85%",
                    "contributions": {"Name": 0.50, "Domain": 0.35},
                },
            ],
        },
    }

    # Store results
    mock_survey_results[survey_id] = results


@router.get("/mock/{survey_id}")
async def get_mock_survey_status(survey_id: str):
    """Get mock survey results if complete."""
    if survey_id in mock_survey_results:
        return mock_survey_results[survey_id]

    return {
        "survey_id": survey_id,
        "status": "running",
        "message": "Mock survey in progress",
    }


@router.get("/mock/test/instant-response")
async def get_instant_mock_response():
    """
    Returns an instant mock survey response for immediate testing.
    No background processing, just immediate results.
    """
    return {
        "survey_id": f"survey_instant_{datetime.utcnow().timestamp()}",
        "status": "complete",
        "summary": {
            "duplicates_found": 47,
            "data_quality_score": 78,
            "grade": "B+",
            "enrichment_opportunities": 15,
            "total_records_scanned": 5000,
            "objects_analyzed": ["Account", "Contact", "Lead"],
            "duplicate_examples": [
                {
                    "records": [
                        {"Name": "Global Industries LLC", "Id": "001xxx005"},
                        {"Name": "Global Industries", "Id": "001xxx006"},
                    ],
                    "score": 0.88,
                    "tier": "LIKELY",
                    "explanation": "High confidence match on multiple fields",
                    "visual": "██████████████████░░ 88%",
                    "contributions": {"Name": 0.40, "Website": 0.30, "Phone": 0.18},
                }
            ],
            "processing_time": 3.5,
            "recommendations": [
                "Enable automatic duplicate prevention rules",
                "Standardize company name formatting",
                "Implement email domain validation",
            ],
        },
    }
