# src/fmatch/saas/api/v2/discovery.py
"""
API endpoints for field discovery management.
"""

from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from typing import Dict, Any, List, Optional
from pydantic import BaseModel
import logging

from ...auth import get_current_user
from ...services.discovery_service import DiscoveryService
# from ...models import User  # User model not implemented yet

logger = logging.getLogger(__name__)

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


class DiscoveryRequest(BaseModel):
    """Request to run field discovery."""

    integration_id: str
    object_types: Optional[List[str]] = None
    use_ai: bool = False
    force_refresh: bool = False


class DiscoveryPolicyResponse(BaseModel):
    """Response with discovery policy details."""

    policy_id: str
    object_type: str
    status: str
    discovered_at: str
    selected_fields: List[str]
    field_explanations: Dict[str, Any]
    thresholds: Dict[str, float]


@router.post("/run")
async def run_discovery(
    request: DiscoveryRequest,
    background_tasks: BackgroundTasks,
    current_user: str = Depends(get_current_user),
) -> Dict[str, Any]:
    """
    Run field discovery for Salesforce objects.

    This endpoint triggers the discovery agent to analyze Salesforce fields
    and determine optimal matching configuration.
    """
    try:
        # Run discovery synchronously - it's fast enough
        service = DiscoveryService()
        results = await service.discover_and_save(
            integration_id=request.integration_id,
            object_types=request.object_types,
            use_ai=request.use_ai,
            force_refresh=request.force_refresh,
        )

        # Count successful discoveries
        successful = sum(1 for r in results.values() if r.get("status") == "discovered")
        total = len(request.object_types) if request.object_types else 3

        return {
            "status": "completed",
            "message": f"Discovery completed: {successful}/{total} objects discovered",
            "integration_id": request.integration_id,
            "results": results,
        }

    except Exception as e:
        logger.error(f"Failed to start discovery: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# Removed _run_discovery_task - now using scheduler with run_discovery_job


@router.get("/policies/{object_type}")
async def get_discovery_policy(
    object_type: str, current_user: str = Depends(get_current_user)
) -> Optional[DiscoveryPolicyResponse]:
    """
    Get active discovery policy for an object type.
    """
    try:
        service = DiscoveryService()
        policy = await service.get_policy_for_matching(
            account_id=current_user,  # current_user is already a string
            object_type=object_type,
        )

        if not policy:
            raise HTTPException(
                status_code=404, detail=f"No policy found for {object_type}"
            )

        return DiscoveryPolicyResponse(
            policy_id=policy.get("id", ""),
            object_type=object_type,
            status="active",
            discovered_at=policy.get("discovered_at", ""),
            selected_fields=policy["fields"],
            field_explanations=policy.get("explanations", {}),
            thresholds=policy["thresholds"],
        )

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to get discovery policy: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/apply-to-survey/{object_type}")
async def apply_discovery_to_survey(
    object_type: str, current_user: str = Depends(get_current_user)
) -> Dict[str, Any]:
    """
    Apply discovered fields to instant survey configuration.
    """
    try:
        service = DiscoveryService()
        result = await service.update_instant_survey_fields(
            account_id=current_user,  # current_user is already a string
            object_type=object_type,
        )

        return result

    except Exception as e:
        logger.error(f"Failed to apply discovery to survey: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/trigger-on-connect")
async def trigger_discovery_on_connect(
    integration_id: str,
    background_tasks: BackgroundTasks = None,  # Keep for compatibility but don't use
) -> Dict[str, Any]:
    """
    Run discovery immediately after Salesforce connection.
    This is fast (3-5 seconds) and reliable.
    """
    try:
        from ...services.discovery_service import DiscoveryService

        # Run discovery synchronously - it's fast and reliable
        service = DiscoveryService()
        results = await service.discover_and_save(
            integration_id=integration_id,
            object_types=["Account", "Contact", "Lead"],
            use_ai=False,
            force_refresh=False,
        )

        # Count successful discoveries
        successful = sum(1 for r in results.values() if r.get("status") == "discovered")

        return {
            "status": "completed",
            "message": f"Discovery completed: {successful}/3 objects discovered",
            "results": results,
        }

    except Exception as e:
        logger.exception(f"Discovery failed: {e}")
        # Don't break OAuth flow - return partial success
        return {
            "status": "partial",
            "message": f"Discovery partially completed: {str(e)}",
            "error": str(e),
        }
