#!/usr/bin/env python3
"""
Phase 1 Ingestion Orchestrator.

DEPRECATED (2026-05-30): Phase 1 is complete. This orchestrator ran once
to seed the brain system. Pipelines are now maintained individually.

Original pipelines:
1. Memory v2 → Brain sync (COMPLETED, archived)
2. Skill library index
3. Session history index
"""

import sys
import os
from pathlib import Path

WIKI_DIR = Path(__file__).parent

def run_pipeline(name, script):
    """Run a single ingestion pipeline."""
    print(f"\n{'='*60}")
    print(f"  {name}")
    print(f"{'='*60}")
    
    script_path = WIKI_DIR / script
    if not script_path.exists():
        print(f"ERROR: Script not found: {script_path}")
        return False
    
    # Execute the script
    import subprocess
    result = subprocess.run(
        [sys.executable, str(script_path)],
        cwd=str(WIKI_DIR),
        capture_output=False,
    )
    
    if result.returncode != 0:
        print(f"\nāŒ Pipeline failed with exit code {result.returncode}")
        return False
    
    print(f"\nāœ“ Pipeline completed")
    return True


def verify_brain_state():
    """Verify final brain state after all pipelines."""
    import json
    
    brain_dir = Path.home() / '.hermes' / 'brain'
    graph_path = brain_dir / 'synapses' / 'graph.json'
    
    if not graph_path.exists():
        print("ERROR: Brain graph not found")
        return
    
    with open(graph_path) as f:
        graph = json.load(f)
    
    events = graph.get('events', {})
    edges = graph.get('edges', [])
    
    # Count by tool
    tool_counts = {}
    for eid, evt in events.items():
        tool = evt.get('tool', '?')
        tool_counts[tool] = tool_counts.get(tool, 0) + 1
    
    print("\n" + "="*60)
    print("FINAL BRAIN STATE")
    print("="*60)
    print(f"Total events: {len(events)}")
    print(f"Total edges: {len(edges)}")
    print(f"\nEvents by tool:")
    for tool, count in sorted(tool_counts.items()):
        print(f"  {tool}: {count}")


if __name__ == '__main__':
    print("="*60)
    print("PHASE 1 INGESTION — Personal Memory Foundation")
    print("="*60)
    
    pipelines = [
        ("Memory v2 → Brain Sync", "memory_v2_brain_ingest.py"),
        ("Skill Library Index", "skills_brain_ingest.py"),
        ("Session History Index", "sessions_brain_ingest.py"),
    ]
    
    results = []
    for name, script in pipelines:
        success = run_pipeline(name, script)
        results.append((name, success))
    
    # Summary
    print("\n" + "="*60)
    print("PHASE 1 SUMMARY")
    print("="*60)
    
    for name, success in results:
        status = "āœ“" if success else "āŒ"
        print(f"  {status} {name}")
    
    # Final state
    verify_brain_state()
    
    # Exit with appropriate code
    all_success = all(s for _, s in results)
    sys.exit(0 if all_success else 1)