"""
Execution Agent v4 - With JSON repair
"""
import requests
import time
import json
import subprocess
import re
from pathlib import Path

AGENT_API = "http://localhost:5017/api/agent_command"

class ExecutionAgent:
    def __init__(self):
        self.tasks_completed = 0
    
    def ask_eden_for_task(self):
        """Ask Eden for task"""
        prompt = """Create ONE AGI component. Give JSON:
{"action": "create_file", "filepath": "/Eden/CORE/meta_learning.py", "content": "class MetaLearning: pass"}"""
        
        try:
            response = requests.post(AGENT_API, json={'message': prompt}, timeout=30)
            return response.json()['response']
        except Exception as e:
            return f"Error: {e}"
    
    def repair_json(self, text):
        """Try to fix common JSON errors"""
        # Find JSON-like content
        match = re.search(r'\{[^}]*\}', text, re.DOTALL)
        if not match:
            return None
        
        json_str = match.group(0)
        
        # Fix common issues
        # Add missing closing quotes
        json_str = re.sub(r'("[^"]*$)', r'\1"', json_str)
        # Fix escaped quotes
        json_str = json_str.replace('\\"', '"')
        
        return json_str
    
    def execute_task(self, json_response):
        """Execute task"""
        print(f"\n🤖 Response: {json_response[:150]}")
        
        try:
            # Try to parse
            if isinstance(json_response, str):
                task = json.loads(json_response)
            else:
                task = json_response
        except json.JSONDecodeError:
            # Try repair
            print("   🔧 Attempting JSON repair...")
            repaired = self.repair_json(json_response)
            if repaired:
                try:
                    task = json.loads(repaired)
                    print(f"   ✅ Repaired: {repaired[:100]}")
                except:
                    print(f"   ❌ Repair failed")
                    return False
            else:
                print("   ❌ No JSON found")
                return False
        
        print(f"   📋 Task: {task}")
        
        action = task.get('action', '')
        filepath = task.get('filepath', '')
        
        try:
            if action == 'create_file':
                content = task.get('content', '')
                
                if filepath.startswith('/Eden/'):
                    Path(filepath).parent.mkdir(parents=True, exist_ok=True)
                    with open(filepath, 'w') as f:
                        f.write(content)
                    print(f"   ✅ CREATED: {filepath}")
                    self.tasks_completed += 1
                    return True
            
            elif action == 'modify_file':
                search = task.get('search', '')
                replace = task.get('replace', '')
                
                if filepath and filepath.startswith('/Eden/'):
                    with open(filepath, 'r') as f:
                        content = f.read()
                    new_content = content.replace(search, replace)
                    with open(filepath, 'w') as f:
                        f.write(new_content)
                    print(f"   ✅ MODIFIED: {filepath}")
                    self.tasks_completed += 1
                    return True
                    
        except Exception as e:
            print(f"   ❌ Error: {e}")
        
        return False
    
    def run(self):
        """Main loop"""
        print("🤖 EXECUTION AGENT v4 - With JSON Repair")
        print("Using /api/agent_command\n")
        
        iteration = 0
        while True:
            try:
                iteration += 1
                print(f"\n{'='*60}")
                print(f"🔄 Cycle {iteration} | Completed: {self.tasks_completed}")
                print(f"{'='*60}")
                
                response = self.ask_eden_for_task()
                self.execute_task(response)
                
                time.sleep(180)
                
            except KeyboardInterrupt:
                print(f"\n🛑 Done! Completed {self.tasks_completed} tasks")
                break
            except Exception as e:
                print(f"❌ Error: {e}")
                time.sleep(60)

if __name__ == '__main__':
    agent = ExecutionAgent()
    agent.run()
