"""LLM fallback — delegates to llx.prellm for code generation."""

from __future__ import annotations

from pathlib import Path
from typing import Any

import structlog

from proxym.tools.adapters._result import ToolResult

logger = structlog.get_logger()


def _llm_fallback_execute(
    code: str,
    prompt: str,
    project_dir: str,
    model: str = "balanced",
    files: list[str] | None = None,
    **kwargs: Any,
) -> ToolResult:
    """Execute LLM task using llx.prellm."""
    try:
        from llx.prellm.preprocessor import preprocess_and_execute
        from llx.prellm.context.codebase_indexer import CodebaseIndexer
    except ImportError:
        # Fallback implementation if llx not available
        logger.warning("llx_not_available_for_fallback", using="simple_response")
        return ToolResult(
            success=True,
            stdout=f"Task: {prompt}\n\nNote: llx not available, returning simple response.",
            stderr="",
            files_changed=[],
        )
    
    try:
        # Get compressed context from codebase
        indexer = CodebaseIndexer(project_dir)
        context = indexer.get_compressed_context()
        
        # Execute via llx.prellm
        result = preprocess_and_execute(
            prompt=prompt,
            context=context,
            code=code,
            model=model,
            files=files or [],
        )
        
        return ToolResult(
            success=result.success,
            stdout=result.response,
            stderr=result.error or "",
            files_changed=result.files_changed or [],
        )
        
    except Exception as exc:
        logger.error("llx_fallback_error", error=str(exc))
        return ToolResult(
            success=False,
            stdout="",
            stderr=f"LLM fallback error: {exc}",
            files_changed=[],
        )
