#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
// PURPOSE: Atomic Brain Cleanse - Physical Deduplication via CRDT.
// [Phase 1.1: Transaction Semantics]
"""

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

# Add Utilities to path

from pulse.core.brain_utils import load_json, save_json, EVIDENCE_DIR, HIPPOCAMPUS_DIR
from pulse.core.pulse_crdt import EvidenceCRDT

CRDT = EvidenceCRDT()

def cleanse_brain():
    print(f"=== Starting Grand Brain Cleanse (Recursive CRDT) ===")
    
    # Target both Public Evidence and Private Episodic chambers
    targets = [EVIDENCE_DIR, HIPPOCAMPUS_DIR / "Private" / "Episodic"]

    for target_dir in targets:
        if not target_dir.exists():
            continue
        print(f"Scanning: {target_dir}")
        for ef in sorted(target_dir.rglob("*.json")):
            items = load_json(ef)
            if not items or not isinstance(items, list):
                continue
                
            original_count = len(items)
            cleansed_items = CRDT.merge(items, [])
            new_count = len(cleansed_items)
            
            if original_count != new_count:
                save_json(ef, cleansed_items)
                print(f"  [CLEANSED] {ef.name}: {original_count} -> {new_count} items")
            else:
                pass

if __name__ == "__main__":
    cleanse_brain()