"""Jump-to-index route for fetching a single segment by index"""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/routes/sample.ipynb.

# %% auto #0
__all__ = ['DEBUG_SAMPLE_ROUTES', 'init_sample_router']

# %% ../../nbs/routes/sample.ipynb #verify-routes-sample-imports
from typing import Dict, Callable, Tuple

from fasthtml.common import APIRouter

from cjm_fasthtml_interactions.core.state_store import get_session_id

from ..models import VerifyUrls
from ..services.verify import VerifyService
from .core import WorkflowStateStore, _load_verify_context
from ..components.sample_segments import render_jump_result

# Debug flag
DEBUG_SAMPLE_ROUTES = False

# %% ../../nbs/routes/sample.ipynb #verify-routes-sample-init
def init_sample_router(
    state_store:WorkflowStateStore,  # The workflow state store
    workflow_id:str,  # The workflow identifier
    prefix:str,  # Route prefix (e.g., "/workflow/verify")
    verify_service:VerifyService,  # Service for graph queries
    urls:VerifyUrls,  # URL bundle (will be populated)
) -> Tuple[APIRouter, Dict[str, Callable]]:  # (router, routes dict)
    """Initialize sample route for jump-to-index segment fetching."""
    router = APIRouter(prefix=prefix)
    routes = {}
    
    @router
    async def sample(request, sess, index:str=""):
        """Fetch a single segment by index."""
        session_id = get_session_id(sess)
        
        if DEBUG_SAMPLE_ROUTES:
            print(f"[SAMPLE_ROUTES] sample called with index: {index!r}")
            print(f"[SAMPLE_ROUTES] session_id: {session_id}")
        
        # Validate index is provided and numeric
        if not index or not index.strip():
            return render_jump_result(error="Please enter an index")
        
        try:
            idx = int(index.strip())
        except ValueError:
            return render_jump_result(error=f"Invalid index: {index}")
        
        # Validate non-negative
        if idx < 0:
            return render_jump_result(error="Index cannot be negative")
        
        # Load context to get document_id
        ctx = _load_verify_context(state_store, workflow_id, session_id)
        
        if DEBUG_SAMPLE_ROUTES:
            print(f"[SAMPLE_ROUTES] document_id: {ctx.document_id}")
        
        if not ctx.document_id:
            return render_jump_result(error="No document loaded")
        
        # Check index is within range
        segment_count = await verify_service.get_segment_count_async(ctx.document_id)
        
        if idx >= segment_count:
            return render_jump_result(
                error=f"Index {idx} out of range (max: {segment_count - 1})"
            )
        
        # Fetch the segment
        sample = await verify_service.get_segment_by_index_async(ctx.document_id, idx)
        
        if sample is None:
            return render_jump_result(error=f"Segment {idx} not found")
        
        if DEBUG_SAMPLE_ROUTES:
            print(f"[SAMPLE_ROUTES] Found segment: index={sample.index}, text={sample.text[:30]}...")
        
        return render_jump_result(sample=sample)
    
    routes["sample"] = sample
    
    return router, routes
