import json
from pathlib import Path
import sys
from datetime import datetime, timezone

pulse_root = Path(r'C:\Users\ovall\Documents\projects\babel_bot\PULSE')
sys.path.insert(0, str(pulse_root))

task_board_path = pulse_root / 'Prefrontal_Cortex' / 'Action_Queue' / 'task_board.json'
data = json.loads(task_board_path.read_text(encoding='utf-8'))

# Gather active tasks
dispatches = data.get('dispatches', [])
tasks = []
for d in dispatches:
    tasks.extend(d.get('tasks', []))

active_clean_tasks = [t for t in tasks if 'CLEAN_INTENTS' in t.get('title', '') and t.get('status') in ['open', 'pending', 'active']]

print(f'Found {len(active_clean_tasks)} active CLEAN_INTENTS tasks. Processing...')

from pulse.admin.retroactive.retroactive_intents_cleaner import clean_intents, WANTS_PROMPT, DONT_WANTS_PROMPT
from pulse.brain.save_writers import append_to_json_list
from pulse.core.pulse_crypto import sign_item

now = datetime.now(timezone.utc).isoformat()

for task in active_clean_tasks:
    mem_data = task.get('memory_data', {})
    batch = mem_data.get('batch', [])
    key = mem_data.get('key', 'want')
    
    print(f'Synthesizing: {task["title"]}...')
    
    try:
        # Determine the correct prompt based on the key
        prompt = WANTS_PROMPT if key == 'want' else DONT_WANTS_PROMPT
        
        # The cleaner takes a list of objects (dicts or strings). If batch is strings, convert to dicts to match extract_text_values expectations.
        entries = [{key: item} if isinstance(item, str) else item for item in batch]
        
        clean_items = clean_intents(
            entries=entries,
            key=key,
            prompt_template=prompt,
            label=f"{key}s"
        )
        
        filepath = pulse_root / 'Hippocampus' / 'Evidence' / 'Intents' / f'{key}s.json'
        
        added = 0
        for item in clean_items:
            # Match schema: rebuild_wants_json / rebuild_dont_wants_json
            if key == 'want':
                entry = {
                    "want": item,
                    "priority": 7,
                    "domain": "general",
                    "visibility": "public",
                    "timestamp": now,
                    "source": "swarm_cleaned",
                    "session_id": "intents_cleaner",
                }
            else:
                entry = {
                    "dont_want": item,
                    "reason": "system_rule",
                    "domain": "general",
                    "visibility": "public",
                    "timestamp": now,
                    "source": "swarm_cleaned",
                    "session_id": "intents_cleaner",
                    "evidence_count": 1,
                    "status": "active",
                }
            
            entry = sign_item(entry, 'swarm_cleaner')
            if append_to_json_list(filepath, entry, dedup_key=key):
                added += 1
                
        task['status'] = 'done'
        task['outcome'] = f'Synthesized {len(batch)} down to {len(clean_items)} unique intents. Appended {added}.'
        print(f'  -> {task["outcome"]}')
    except Exception as e:
        print(f'  -> Error: {e}')

task_board_path.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding='utf-8')
print('Task board updated successfully.')
