"""
Celery tasks for LLM Manager — ported from Spelunker.
"""

import logging

from celery import shared_task

from .models import LLMApi
from .services import test_llm_api

logger = logging.getLogger(__name__)


@shared_task(name="llm_manager.validate_all_llm_apis")
def validate_all_llm_apis():
    """
    Periodic task to validate all active LLM APIs and discover models.

    Schedule via Celery Beat (e.g. hourly or daily).
    """
    logger.info("Starting periodic LLM API validation")
    active_apis = LLMApi.objects.filter(is_active=True)

    if not active_apis.exists():
        logger.info("No active APIs to validate")
        return {"status": "completed", "tested": 0, "successful": 0, "failed": 0}

    results = {
        "status": "completed",
        "tested": 0,
        "successful": 0,
        "failed": 0,
        "models_added": 0,
        "models_updated": 0,
        "models_deactivated": 0,
        "details": [],
    }

    for api in active_apis:
        results["tested"] += 1
        try:
            result = test_llm_api(api)
            if result["success"]:
                results["successful"] += 1
                results["models_added"] += result["models_added"]
                results["models_updated"] += result["models_updated"]
                results["models_deactivated"] += result["models_deactivated"]
            else:
                results["failed"] += 1
            results["details"].append(
                {
                    "api_name": api.name,
                    "success": result["success"],
                    "message": result.get("message") or result.get("error", ""),
                }
            )
        except Exception as e:
            results["failed"] += 1
            results["details"].append(
                {"api_name": api.name, "success": False, "message": str(e)}
            )
            logger.error("Unexpected error validating %s: %s", api.name, e, exc_info=True)

    logger.info(
        "Completed LLM API validation: %d/%d successful, %d failed",
        results["successful"],
        results["tested"],
        results["failed"],
    )
    return results


@shared_task(name="llm_manager.validate_single_api")
def validate_single_api(api_id):
    """Validate a single LLM API by ID."""
    try:
        api = LLMApi.objects.get(id=api_id)
        return test_llm_api(api)
    except LLMApi.DoesNotExist:
        msg = f"LLM API with id {api_id} not found"
        logger.error(msg)
        return {"success": False, "error": msg}
    except Exception as e:
        logger.error("Error validating API %s: %s", api_id, e, exc_info=True)
        return {"success": False, "error": str(e)}
