#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Reasoning Tools for PULSE Workers

Implements NLP Gap 1 from QR8: Analogical Reasoning Chains. Provides tools
for multi-step "Chain-of-Thought" reasoning.
"""
import logging
from typing import Dict, Any

log = logging.getLogger("pulse.worker_tools_reasoning")

def tool_reason_by_analogy_chain(prompt: str, steps: int = 3) -> str:
    """
    Performs multi-step analogical reasoning to solve a complex problem.

    Args:
        prompt: The complex question or "what if" scenario.
        steps: The number of reasoning steps to perform (capped at 5).

    Returns:
        A string containing the final conclusion of the reasoning chain.
    """
    try:
        from pulse.graph.analogy import find_analogies
        from pulse.core.llm_router import dispatch

        reasoning_chain = f"Initial Prompt: {prompt}
"
        current_prompt = prompt
        steps = min(steps, 5) # Hard cap to prevent runaway loops

        for i in range(steps):
            reasoning_chain += f"
--- Step {i+1}/{steps} ---
"

            # 1. Find an analogy for the current problem state
            analogies = find_analogies(current_prompt, top_k=1)
            if not analogies:
                reasoning_chain += "No further analogies found. Concluding reasoning chain."
                break
            
            analogy = analogies[0]
            reasoning_chain += f"Found Analogy: {analogy['text']} (Similarity: {analogy['similarity']:.2f})
"

            # 2. Use an LLM to interpret the implication of the analogy
            interpretation_prompt = (
                f"Given the current problem: '{current_prompt}'
"
                f"And the analogous situation: '{analogy['text']}'

"
                "What is the specific, actionable implication of this analogy? "
                "Based on this, what is the very next logical step or question to solve the problem? "
                "Be concise."
            )
            
            implication = dispatch(interpretation_prompt, task_type="fast", confidence=0.7)
            reasoning_chain += f"Implication: {implication}
"

            # 3. Update the prompt for the next iteration
            current_prompt = f"Original problem: {prompt}
Previous step: {implication}"

        final_conclusion_prompt = (
            "Based on the following reasoning chain, what is the final conclusion or answer "
            f"to the initial prompt: '{prompt}'?

"
            f"REASONING CHAIN:
{reasoning_chain}"
        )

        conclusion = dispatch(final_conclusion_prompt, task_type="standard", confidence=0.8)
        return f"Conclusion from reasoning chain:
{conclusion}

Full Chain:
{reasoning_chain}"

    except Exception as e:
        log.error(f"Analogical reasoning chain failed: {e}", exc_info=True)
        return f"ERROR: The reasoning chain failed due to an internal error: {e}"

