#!/usr/bin/env python3
"""
EDEN SOAR REASONER - Routes synthesis tasks to self-improving SOAR
"""
import sys
sys.path.insert(0, '/Eden/CORE')

from eden_soar_integration import EdenSOAR
from typing import Dict, Any, List
import re
import ast

class SOARReasoner:
    def __init__(self):
        self.soar = EdenSOAR()
        self.synthesis_keywords = [
            'write a function', 'create a program', 'code that',
            'implement', 'algorithm', 'solve this', 'transform',
            'given input', 'returns', 'write code', 'python'
        ]
        
    def is_synthesis_task(self, text: str) -> bool:
        text_lower = text.lower()
        return any(kw in text_lower for kw in self.synthesis_keywords)
    
    def extract_examples(self, text: str) -> List[Dict]:
        """Extract input/output examples from text"""
        examples = []
        
        # Process line by line for cleaner extraction
        lines = text.split('\n')
        for line in lines:
            line_lower = line.lower()
            if 'input' in line_lower and 'output' in line_lower:
                # Try to find bracketed expressions [...]
                brackets = re.findall(r'\[([^\]]+)\]', line)
                if len(brackets) >= 2:
                    try:
                        inp = ast.literal_eval(f"[{brackets[0]}]")
                        out = ast.literal_eval(f"[{brackets[1]}]")
                        examples.append({"input": inp, "output": out})
                        continue
                    except:
                        pass
                
                # Try quoted strings "..."
                quotes = re.findall(r'"([^"]+)"', line)
                if len(quotes) >= 2:
                    examples.append({"input": quotes[0], "output": quotes[1]})
                    continue
                    
                # Try single values after input/output
                match = re.search(r'input[:\s]+(\d+)[^\d]+output[:\s]+(-?\d+)', line_lower)
                if match:
                    examples.append({"input": int(match.group(1)), "output": int(match.group(2))})
        
        return examples
    
    def reason(self, query: str, examples: List[Dict] = None) -> Dict[str, Any]:
        """Use SOAR to synthesize a solution"""
        if examples is None:
            examples = self.extract_examples(query)
        
        if not examples:
            return {
                "source": "soar",
                "success": False,
                "response": "Need input/output examples. Format: input: [1,2,3] -> output: [2,4,6]",
                "confidence": 0.0
            }
        
        solution = self.soar.evolve(query, examples, max_iterations=5, samples_per_iteration=3)
        
        if solution:
            all_correct = True
            for ex in examples:
                success, output, error = self.soar.execute_program(solution, ex['input'])
                if not success or output != ex['output']:
                    all_correct = False
                    break
            
            return {
                "source": "soar",
                "success": all_correct,
                "program": solution,
                "response": f"```python\n{solution}\n```",
                "confidence": 1.0 if all_correct else 0.7,
                "training_samples": len(self.soar.get_training_data())
            }
        
        return {
            "source": "soar", 
            "success": False,
            "response": "Couldn't solve, but collected training data.",
            "confidence": 0.3
        }

if __name__ == "__main__":
    reasoner = SOARReasoner()
    
    query = """Write a function to double numbers.
    input: [1, 2, 3] -> output: [2, 4, 6]
    input: [5] -> output: [10]
    """
    
    print("Testing extraction:")
    examples = reasoner.extract_examples(query)
    print(f"Examples: {examples}")
    
    print("\nTesting SOAR:")
    result = reasoner.reason(query)
    print(f"Success: {result['success']}")
    if result.get('program'):
        print(f"Program:\n{result['program']}")
