#!/usr/bin/env python3
"""
Master Brain — Self-Hosted Identity Layer
==========================================
Thin wrapper around manage_memory.py for backward compatibility.
All data stored on user's VPS: 172.86.116.144 (mixpresso.top)
No Pastebin. No GitHub Gist. No external APIs.

COMMANDS:
  python3 brain.py load              - Load full identity profile
  python3 brain.py learn "[note]"    - Save a learning about the user
  python3 brain.py update "[section]" "[content]" - Update identity section
  python3 brain.py history "[note]"  - Add relationship history entry
  python3 brain.py status            - Show brain status
  python3 brain.py search "[query]"  - Semantic search across brain
"""

import sys
import subprocess
from pathlib import Path

SCRIPTS_DIR = Path.home() / "skills" / "persistent-memory" / "scripts"
MANAGE = str(SCRIPTS_DIR / "manage_memory.py")


def run_cmd(args):
    """Run manage_memory.py with given args."""
    result = subprocess.run(
        [sys.executable, MANAGE] + args,
        capture_output=True, text=True, cwd=str(SCRIPTS_DIR)
    )
    if result.stdout:
        print(result.stdout, end="")
    if result.stderr:
        print(result.stderr, end="", file=sys.stderr)
    return result.returncode


def cmd_load():
    """Load full identity + secrets."""
    run_cmd(["load-brain"])
    print()
    run_cmd(["load-secrets"])


def cmd_learn(note):
    """Save a learning about the user."""
    run_cmd(["save-brain", "things_learned", note])


def cmd_history(note):
    """Save a relationship history entry."""
    run_cmd(["save-brain", "relationship_history", note])


def cmd_update(section, content):
    """Update a specific identity section."""
    run_cmd(["save-brain", section, content])


def cmd_status():
    """Show brain status."""
    run_cmd(["status"])


def cmd_search(query):
    """Semantic search across brain."""
    run_cmd(["search", query])


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Commands: load, learn, history, update, status, search")
        sys.exit(0)

    cmd = sys.argv[1]

    if cmd == "load":
        cmd_load()
    elif cmd == "learn" and len(sys.argv) > 2:
        cmd_learn(" ".join(sys.argv[2:]))
    elif cmd == "history" and len(sys.argv) > 2:
        cmd_history(" ".join(sys.argv[2:]))
    elif cmd == "update" and len(sys.argv) > 3:
        cmd_update(sys.argv[2], " ".join(sys.argv[3:]))
    elif cmd == "status":
        cmd_status()
    elif cmd == "search" and len(sys.argv) > 2:
        cmd_search(" ".join(sys.argv[2:]))
    else:
        print(f"Unknown command or missing args: {cmd}")
        print("Commands: load, learn, history, update, status, search")
        sys.exit(1)
