"""
Curriculum standards search functionality.

This module provides tools for searching curriculum standards via the InceptAPI.
"""

import logging
import time
import json
from typing import Optional, Union

import httpx

from inceptbench_new.config import settings
from inceptbench_new.core.input_models import RequestMetadata

logger = logging.getLogger(__name__)


async def get_curriculum_context(
    content: str, 
    curriculum: str = "common_core",
    request_metadata: Optional[RequestMetadata] = None
) -> str:
    """
    Get curriculum context by calling the InceptAPI curriculum search endpoint.
    
    The API handles all complexity including:
    - Content preparation and cleaning
    - Extracting explicit curriculum standards from content
    - Vector store search across curriculum databases
    - Deduplication of results
    
    Args:
        content: The educational content to analyze
        curriculum: Curriculum name (default: "common_core")
        request_metadata: Optional metadata about the content generation request
        
    Returns:
        Formatted curriculum context string, or empty string if none found
    """
    start_time = time.time()
    
    try:
        # Determine search query based on available information
        search_query = content
        search_source = "content"
        
        if request_metadata:
            # If explicit skills provided, prioritize them for search (Intent-based search)
            if request_metadata.skills:
                search_source = "skills (intent)"
                if isinstance(request_metadata.skills, dict):
                    # For dict, we prioritize looking for specific standard IDs if available
                    # but send the whole object structure to let the search backend handle it
                    search_query = json.dumps(request_metadata.skills)
                    
                    # If we have a specific ID, we might want to ensure it's prominent
                    # (Though JSON dump usually works well for semantic search)
                else:
                    search_query = str(request_metadata.skills)
                
                # Append grade/subject for additional context
                if request_metadata.grade:
                    search_query += f" Grade {request_metadata.grade}"
                if request_metadata.subject:
                    search_query += f" {request_metadata.subject}"
            
            else:
                # No explicit skills, use content but enrich with grade/subject from metadata
                search_source = "content + metadata"
                context_parts = []
                if request_metadata.grade:
                    context_parts.append(f"Grade {request_metadata.grade}")
                if request_metadata.subject:
                    context_parts.append(request_metadata.subject)
                
                if context_parts:
                    # Prepend context to content
                    search_query = f"{' '.join(context_parts)}\n\n{content}"

        logger.info(
            f"Searching {curriculum} curriculum standards using {search_source}. "
            f"Query length: {len(search_query)}"
        )
        
        # Call the InceptAPI curriculum search endpoint
        headers = {"X-API-Key": settings.INCEPT_API_KEY} if settings.INCEPT_API_KEY else {}
        async with httpx.AsyncClient(timeout=settings.CURRICULUM_SEARCH_TIMEOUT) as client:
            headers = {}
            if settings.INCEPT_API_KEY:
                headers["Authorization"] = f"Bearer {settings.INCEPT_API_KEY}"
            
            response = await client.post(
                f"{settings.INCEPTAPI_BASE_URL}/curriculum-search",
                json={
                    "prompt": search_query,
                    "curriculum_name": curriculum
                },
                headers=headers
            )
            response.raise_for_status()
            
            data = response.json()
            results = data.get("results", "")
            
            if results:
                logger.info(f"Curriculum standards search completed in {time.time() - start_time:.2f}s")
                return f"\n\nRelevant Curriculum Context:\n{results}"
            else:
                logger.warning(f"No curriculum standards found after {time.time() - start_time:.2f}s")
                return ""
                
    except httpx.HTTPStatusError as e:
        logger.error(f"HTTP error from curriculum API after {time.time() - start_time:.2f}s: "
                    f"{e.response.status_code} - {e.response.text}")
        return ""
    except Exception as e:
        logger.warning(f"Could not retrieve curriculum context after {time.time() - start_time:.2f}s: {e}")
        return ""
