#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
PULSE Brain Scaffold Generator

Dynamically scans the brain anatomy and ensures all required folders exist.
Runs on first clone or after any refactor that adds new brain regions.

Usage:
    python pulse_scaffold.py           # Create missing folders
    python pulse_scaffold.py --check   # Dry run — report what's missing
    python pulse_scaffold.py --export  # Export current structure to manifest
"""
import sys
import json
from pathlib import Path

SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR.parent.parent.parent
MANIFEST_FILE = ROOT_DIR / "pulse" / "config" / "brain_manifest.json"

# Brain regions that MUST exist for PULSE to function.
# This is auto-generated by --export and checked by --check / default run.
# Add new regions here OR run --export to auto-detect from a working brain.
DEFAULT_STRUCTURE = [
    # Runtime state
    "state",
    "state/worker_logs",

    # Corpus Callosum (stable knowledge)
    "Corpus_Callosum/Protocols",
    "Corpus_Callosum/Archive",

    # Hippocampus (dynamic memory — 6 flat regions)
    "Hippocampus/Evidence",
    "Hippocampus/Evidence/Sessions",
    "Hippocampus/Evidence/Decisions",
    "Hippocampus/Evidence/Intents",
    "Hippocampus/Evidence/Anti_Patterns",
    "Hippocampus/Evidence/Metrics",
    "Hippocampus/Failures",
    "Hippocampus/Knowledge",
    "Hippocampus/Lessons",
    "Hippocampus/Patterns",

    # Prefrontal Cortex (executive function)
    "Prefrontal_Cortex/Action_Queue",
    "Prefrontal_Cortex/Action_Queue/completed",
    "Prefrontal_Cortex/Action_Queue/rejected",
    "Prefrontal_Cortex/Working_Memory",

    # Personal Plans (user-private)
    "Personal_Plans",
]

# Folders to SKIP when scanning (not part of brain anatomy)
SKIP_PATTERNS = {"__pycache__", ".git", ".vscode", ".idea", "node_modules", "dist", "build"}


def load_manifest():
    """Load brain structure from manifest if it exists, else use defaults."""
    if MANIFEST_FILE.exists():
        try:
            data = json.loads(MANIFEST_FILE.read_text(encoding="utf-8"))
            return data.get("brain_regions", DEFAULT_STRUCTURE)
        except (json.JSONDecodeError, KeyError):
            pass
    return DEFAULT_STRUCTURE


def scan_current_structure():
    """Dynamically scan the current brain for all directories."""
    dirs = []
    for p in sorted(ROOT_DIR.rglob("*")):
        if not p.is_dir():
            continue
        rel = p.relative_to(ROOT_DIR).as_posix()
        if any(skip in rel.split("/") for skip in SKIP_PATTERNS):
            continue
        # Skip hidden dirs (except .claude and .cursor which are part of the brain)
        parts = rel.split("/")
        if any(part.startswith(".") and part not in (".claude", ".cursor") for part in parts):
            continue
        dirs.append(rel)
    return dirs


def scaffold(dry_run=False):
    """Create all missing brain folders."""
    regions = load_manifest()
    created = []
    existing = []

    for region in regions:
        path = ROOT_DIR / region
        if path.exists():
            existing.append(region)
        else:
            if not dry_run:
                path.mkdir(parents=True, exist_ok=True)
            created.append(region)

    print(f"[PULSE Scaffold] Brain anatomy: {len(regions)} regions")
    print(f"  Already exist: {len(existing)}")
    print(f"  {'Would create' if dry_run else 'Created'}: {len(created)}")

    if created:
        for c in created:
            print(f"    + {c}")

    if not created:
        print("  Brain structure is complete. No scaffolding needed.")

    return created


def export_manifest():
    """Export current brain structure to manifest for future scaffolds."""
    dirs = scan_current_structure()
    manifest = {
        "version": "1.0",
        "description": "Auto-generated brain anatomy manifest. Used by pulse_scaffold.py to recreate folder structure on fresh clones.",
        "brain_regions": dirs
    }
    MANIFEST_FILE.parent.mkdir(parents=True, exist_ok=True)
    MANIFEST_FILE.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
    print(f"[PULSE Scaffold] Exported {len(dirs)} regions to {MANIFEST_FILE.name}")
    return dirs


if __name__ == "__main__":
    if "--export" in sys.argv:
        export_manifest()
    elif "--check" in sys.argv:
        scaffold(dry_run=True)
    else:
        scaffold()
