import json
from pathlib import Path
import sys

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

from pulse.core.pulse_crypto import sign_item

def retroactively_sign_json_file(filepath):
    path = Path(filepath)
    if not path.exists():
        return
    try:
        data = json.loads(path.read_text(encoding='utf-8'))
    except Exception as e:
        print(f"Failed to read {path.name}: {e}")
        return

    modified = False
    
    # Process if it's a list
    if isinstance(data, list):
        for i in range(len(data)):
            if isinstance(data[i], dict) and '_signature' not in data[i]:
                # Sign the item. Default to 'retroactive_signer' or extract agent if exists
                agent = data[i].get('source_agent', data[i].get('agent', 'pulse_swarm'))
                data[i] = sign_item(data[i], agent)
                modified = True
    elif isinstance(data, dict):
        # some files have {"decisions": [...]}
        for key in data.keys():
            if isinstance(data[key], list):
                for i in range(len(data[key])):
                    if isinstance(data[key][i], dict) and '_signature' not in data[key][i]:
                        agent = data[key][i].get('source_agent', data[key][i].get('agent', 'pulse_swarm'))
                        data[key][i] = sign_item(data[key][i], agent)
                        modified = True

    if modified:
        path.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding='utf-8')
        print(f"Signed missing items in {path.name}")

files_to_check = [
    r"C:\Users\ovall\Documents\projects\babel_bot\PULSE\Hippocampus\Evidence\Intents\wants.json",
    r"C:\Users\ovall\Documents\projects\babel_bot\PULSE\Hippocampus\Evidence\Intents\dont_wants.json",
    r"C:\Users\ovall\Documents\projects\babel_bot\PULSE\Hippocampus\Evidence\Intents\strategic_intents.json",
    r"C:\Users\ovall\Documents\projects\babel_bot\PULSE\Hippocampus\Patterns\schemas.json"
]

for f in files_to_check:
    retroactively_sign_json_file(f)

print("Retroactive signing complete.")
