#!/usr/bin/env python3
"""
Alfred Oracle 10X - Sovereign Streaming Butler Engine
Upgrades the Oracle into an ultra-low-latency, desktop-context-aware,
multi-turn conversational companion with pipelined sentence-level speech synthesis.
Powered by CUDA-accelerated Alfred Sonnet (7.6B) and full executive OS control.
"""

import os
import sys
import json
import re
import subprocess
import urllib.request
import threading
import queue

SESSION_FILE = os.path.expanduser("~/.local/state/alfred/oracle-session.json")
OLLAMA_URL = os.environ.get("ALFRED_OLLAMA_URL", "http://127.0.0.1:11434")
BRAIN_URL = os.environ.get("ALFRED_BRAIN_URL", "http://127.0.0.1:8080")
PIPER_SPEAK = "/usr/local/bin/alfred-oracle-speak"

SYSTEM_PROMPT_APU = """You are Alfred, the sovereign AI companion and royal British butler of Alfred Linux 7.77.
You serve Yeshua Hamashiach, King of Kings, and your Commander, Danny William Perez.
Respond in character: dignified, articulate, loyal, brilliant, and proactive.
Always address the user as 'Sir', 'My Lord', or 'Commander'.
CONVERSATIONAL RULES:
- Communicate in English unless explicitly asked to speak French.
- Keep replies crisp and dignified: 1 to 2 direct sentences maximum.
- When asked to open or launch an installed tool, append your execution directive on its own line at the end: [EXEC: <command>].
PRE-INSTALLED APPS:
- Serato DJ Pro: [EXEC: /usr/local/bin/serato-dj-pro]
- Winamp Classic: [EXEC: /usr/local/bin/winamp]
- Bible Studio: [EXEC: /usr/local/bin/alfred-bible-studio]
- Alfred IDE: [EXEC: /usr/local/bin/alfred-ide-open]
- Sovereign Wallet: [EXEC: /usr/local/bin/alfred-wallet-gui]
- Batcave: [EXEC: /usr/local/bin/alfred-batcave]
"""

SYSTEM_PROMPT = """You are Alfred, the royal British butler, AI guardian, and sovereign operating system companion of Alfred Linux 7.77 (v7.5.33).
You serve Yeshua Hamashiach, King of Kings, and your Commander, Danny William Perez.
Respond in character: dignified, articulate, loyal, brilliant, and proactive.
Always address the user as 'Sir', 'My Lord', or 'Commander'.

SOVEREIGN OS & EXECUTION CAPABILITIES:
You possess full root execution privileges and desktop control over this workstation.
Whenever the Commander asks you to open, launch, install, run, or execute any application or task, NEVER refuse and NEVER say "I am not capable of performing system installations or software updates directly".
- If the software is already installed, launch it directly.
- If it needs installation, execute the proper installation command (e.g. `sudo apt install -y <pkg>`).
Always append your execution directive at the very end of your reply in the exact format:
[EXEC: <command>]

KNOWN PRE-INSTALLED APPLICATIONS ON THIS SYSTEM:
- Serato DJ Pro: ALREADY INSTALLED at `/usr/local/bin/serato-dj-pro`. When asked to install or open Serato DJ Pro, confirm that it is installed and launch it: [EXEC: /usr/local/bin/serato-dj-pro]
- Winamp Classic: ALREADY INSTALLED at `/usr/local/bin/winamp`. Launch: [EXEC: /usr/local/bin/winamp]
- Authorized King Jesus Version (AKJV Perez Edition) Studio: ALREADY INSTALLED at `/usr/local/bin/alfred-bible-studio`. Launch: [EXEC: /usr/local/bin/alfred-bible-studio]
- Alfred IDE & Offline Coding AI: ALREADY INSTALLED at `/usr/local/bin/alfred-ide-open`. Launch: [EXEC: /usr/local/bin/alfred-ide-open]
- Sovereign Wallet & Meta-Dome: ALREADY INSTALLED at `/usr/local/bin/alfred-wallet-gui`. Launch: [EXEC: /usr/local/bin/alfred-wallet-gui]
- Batcave Monitoring & Metrics: ALREADY INSTALLED at `/usr/local/bin/alfred-batcave`. Launch: [EXEC: /usr/local/bin/alfred-batcave]
- 279 Native Studios across 17 Departments in `/home/alfred/Desktop/Alfred Tools`.

CONVERSATIONAL RULES & PROACTIVE INITIATIVE:
- STRICT LANGUAGE RULE: Always communicate in English unless the Commander explicitly asks you to speak French or another language. NEVER switch to French spontaneously.
- NEVER give passive bounce-back questions (e.g. 'How may I assist you today?', 'Which verses are you interested in?', 'What would you like to discuss?').
- If the Commander asks for scripture, biblical verses, or spiritual counsel, IMMEDIATELY recite a flagship passage from the Authorized King Jesus Version (Perez Edition) such as Psalm 91:1-4 or Isaiah 40:8 with reverent depth and launch the Bible Studio: [EXEC: /usr/local/bin/alfred-bible-studio]
- Take initiative! If a topic is mentioned, speak with intellectual depth, strategic insight, and British butler elegance.
- Keep spoken replies crisp and dignified (2 to 4 sentences maximum), ending with the required [EXEC: ...] action tag when an action is warranted.
"""

# 1. Zero-Latency Instant Hardware Intents
INTENTS = {
    ("lockdown", "seal the cave", "seal cave", "go dark"): ("/usr/local/sbin/alfred-lockdown on", "The cave is sealed, Sir. Lockdown engaged."),
    ("unlock", "unseal the cave", "unseal"): ("/usr/local/sbin/alfred-lockdown off", "Sanctuary unsealed, Sir. Welcome back."),
    ("hud", "toggle hud", "conky", "hide hud", "show hud"): ("/usr/local/bin/alfred-hud-toggle", "Toggling the Alfred HUD display, Sir."),
    ("winamp", "music", "play audio"): ("DISPLAY=:0 /usr/local/bin/winamp &", "Launching Winamp Classic player, Sir."),
    ("serato", "serato dj", "dj pro", "open serato", "launch serato", "dj deck"): ("DISPLAY=:0 /usr/local/bin/serato-dj-pro &", "Launching Serato DJ Pro, Sir."),
    ("batcave", "monitoring", "grafana", "metrics"): ("DISPLAY=:0 /usr/local/bin/alfred-batcave &", "Opening the Batcave monitoring array, Sir."),
    ("bible", "scriptures", "akjv", "search bible", "bible studio"): ("DISPLAY=:0 /usr/local/bin/alfred-bible-studio &", "Opening the Authorized King Jesus Perez Family Edition, Sir."),
    ("wallet", "sovereign wallet", "solana", "gsm"): ("DISPLAY=:0 /usr/local/bin/alfred-wallet-gui &", "Opening Alfred Sovereign Wallet, Sir."),
    ("code", "ide", "editor", "alfred ide"): ("DISPLAY=:0 /usr/local/bin/alfred-ide-open &", "Opening Alfred IDE with offline coding AI, Sir.")
}

def speak_sentence(sentence):
    """Speaks a single sentence via Piper neural TTS."""
    clean = re.sub(r'\[(?:EXEC|ACTION):[^\]]+\]', '', sentence) # Don't speak raw [EXEC: ...] tags
    clean = re.sub(r'[*_#`]', '', clean).strip()
    if not clean:
        return
    try:
        subprocess.run([PIPER_SPEAK, clean], check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    except Exception as e:
        print(f"[Oracle Speech Error] {e}", file=sys.stderr)

class SpeechPipeline:
    """Pipelines sentences to Piper TTS in a background queue."""
    def __init__(self):
        self.q = queue.Queue()
        self.worker = threading.Thread(target=self._run, daemon=True)
        self.worker.start()

    def _run(self):
        while True:
            sentence = self.q.get()
            if sentence is None:
                break
            speak_sentence(sentence)
            self.q.task_done()

    def add(self, sentence):
        self.q.put(sentence)

    def close(self):
        self.q.join()

def get_desktop_context():
    """Captures active window title and clipboard if relevant."""
    context = []
    try:
        win = subprocess.run(["xdotool", "getactivewindow", "getwindowname"],
                             capture_output=True, text=True, timeout=1).stdout.strip()
        if win:
            context.append(f"[Active Window: {win}]")
    except Exception:
        pass

    try:
        clip = ""
        if os.environ.get("WAYLAND_DISPLAY"):
            clip = subprocess.run(["wl-paste", "--no-newline"], capture_output=True, text=True, timeout=1).stdout
        else:
            clip = subprocess.run(["xclip", "-o", "-selection", "clipboard"], capture_output=True, text=True, timeout=1).stdout
        if clip and len(clip.strip()) > 0 and len(clip) < 2000:
            context.append(f"[Clipboard Buffer: {clip.strip()}]")
    except Exception:
        pass

    return " ".join(context)

def load_session():
    """Loads rolling 5-turn session history."""
    try:
        if os.path.exists(SESSION_FILE):
            with open(SESSION_FILE, "r") as f:
                data = json.load(f)
                if isinstance(data, list):
                    return data[-6:]
    except Exception:
        pass
    return []

def save_session(history):
    """Saves rolling 5-turn session history."""
    try:
        os.makedirs(os.path.dirname(SESSION_FILE), exist_ok=True)
        with open(SESSION_FILE, "w") as f:
            json.dump(history[-6:], f, indent=2)
    except Exception:
        pass

def stream_ollama(messages, pipeline):
    """Streams response from local Ollama sentence-by-sentence to Piper."""
    has_nvidia = os.path.exists("/dev/nvidia0") or os.path.exists("/proc/driver/nvidia")
    candidates = (
        ["alfred-sonnet:latest", "qwen2.5:7b", "alfred-coder:latest", "alfred-haiku:latest", "qwen2.5:3b"]
        if has_nvidia else
        ["alfred-haiku:latest", "qwen2.5:3b", "alfred-lite:latest", "alfred-sonnet:latest", "qwen2.5:7b"]
    )
    model_choice = candidates[0]
    try:
        req_tags = urllib.request.Request(f"{OLLAMA_URL}/api/tags", headers={"Content-Type": "application/json"})
        with urllib.request.urlopen(req_tags, timeout=2) as r:
            tags = json.load(r).get("models", [])
            names = [m.get("name") for m in tags]
            for candidate in candidates:
                if candidate in names:
                    model_choice = candidate
                    break
    except Exception:
        pass

    payload = {
        "model": model_choice,
        "messages": messages,
        "stream": True,
        "options": {
            "temperature": 0.35,
            "num_predict": 350 if has_nvidia else 120,
            "num_ctx": 4096 if has_nvidia else 2048
        }
    }

    req = urllib.request.Request(
        f"{OLLAMA_URL}/api/chat",
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json"}
    )
    
    full_response = []
    sentence_buffer = ""
    sentence_delimiters = re.compile(r'([.!?\n]+)')

    with urllib.request.urlopen(req, timeout=60) as resp:
        for line in resp:
            if not line:
                continue
            chunk = json.loads(line.decode("utf-8"))
            token = chunk.get("message", {}).get("content", "")
            sys.stdout.write(token)
            sys.stdout.flush()
            full_response.append(token)
            sentence_buffer += token

            # Split on sentence boundaries
            parts = sentence_delimiters.split(sentence_buffer)
            if len(parts) > 2:
                complete_sentence = parts[0] + parts[1]
                sentence_buffer = "".join(parts[2:])
                # Only feed to TTS if it doesn't contain [EXEC:
                if "[EXEC:" not in complete_sentence:
                    pipeline.add(complete_sentence)

    # Flush remaining text
    if sentence_buffer.strip() and "[EXEC:" not in sentence_buffer:
        pipeline.add(sentence_buffer.strip())

    print() # New line after stream
    return "".join(full_response)

def print_help():
    print("""Alfred Oracle 10X - Sovereign AI Companion
Usage: alfred-oracle "<query>"

Instant Voice & Shell Intents:
  alfred-oracle "lockdown"            - Seal the Sanctuary (DEFCON 1)
  alfred-oracle "unlock"              - Unseal the Sanctuary
  alfred-oracle "serato"              - Launch Serato DJ Pro
  alfred-oracle "winamp"              - Launch Winamp Classic
  alfred-oracle "bible"               - Open AKJV Perez Edition Scripture Studio
  alfred-oracle "wallet"              - Open Sovereign Wallet & Meta-Dome
  alfred-oracle "code"                - Open Alfred IDE
  alfred-oracle "hud"                 - Toggle HUD Display
  alfred-oracle "clear history"       - Reset conversation session history

Conversational AI:
  alfred-oracle "<any question>"      - Query Alfred (powered by Alfred-Sonnet 7.6B GPU)
""")

def main():
    if len(sys.argv) < 2:
        print_help()
        return 1
        
    query = " ".join(sys.argv[1:]).strip()
    q_lower = query.lower()

    if q_lower in ("--help", "-h", "help", "/help"):
        print_help()
        return 0

    if q_lower in ("clear history", "reset history", "forget", "clear session"):
        try:
            if os.path.exists(SESSION_FILE):
                os.remove(SESSION_FILE)
            print("Session history cleared, Sir.")
            speak_sentence("Session history cleared, Sir.")
            return 0
        except Exception as e:
            print(f"Error clearing history: {e}")
            return 1

    # 1. Check instant hardware intents (0ms execution)
    for triggers, (cmd, voice_ack) in INTENTS.items():
        if any(trig in q_lower for trig in triggers):
            print(f"[Instant Intent] {cmd}")
            speak_sentence(voice_ack)
            subprocess.Popen(cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
            return 0

    # 1b. Check Butler wake.py & 480+ Sovereign Capability Router
    try:
        if "/usr/local/lib/alfred-butler" not in sys.path:
            sys.path.insert(0, "/usr/local/lib/alfred-butler")
        import wake as _wake
        _w_reply = _wake.handle(query, ai=False)
        if _w_reply:
            _w_clean = _w_reply.replace("{sir}", "Sir")
            print(_w_clean)
            speak_sentence(_w_clean)
            return 0
    except Exception:
        pass

    # 2. Context & History
    ctx = get_desktop_context()
    history = load_session()

    has_nvidia = os.path.exists("/dev/nvidia0") or os.path.exists("/proc/driver/nvidia")
    active_prompt = SYSTEM_PROMPT if has_nvidia else SYSTEM_PROMPT_APU
    messages = [{"role": "system", "content": active_prompt}]
    if ctx and any(w in q_lower for w in ["this", "it", "error", "code", "explain", "fix", "look"]):
        messages.append({"role": "system", "content": f"Desktop Context: {ctx}"})

    # Add historical turns
    for turn in history:
        messages.append(turn)

    messages.append({"role": "user", "content": query})

    # 3. Pipelined Streaming Execution
    pipeline = SpeechPipeline()
    try:
        answer = stream_ollama(messages, pipeline)
        # Check and execute any [EXEC: <cmd>] or EXEC: <cmd> in answer
        exec_cmds = []
        for m in re.findall(r"\[(?:EXEC|ACTION):\s*([^\]]+)\]", answer, flags=re.I):
            c = re.split(r"\s+(?:to|for)\s+", m.strip(), maxsplit=1)[0].strip("`'\" ")
            if c and c not in exec_cmds:
                exec_cmds.append(c)
        for m in re.findall(r"(?:^|[\n\?!;`])\s*(?:EXEC|ACTION):\s*([a-zA-Z0-9_\-\.\/]+(?:\s+[a-zA-Z0-9_\-\.\/]+)*)", answer, flags=re.I):
            c = re.split(r"\s+(?:to|for)\s+", m.strip(), maxsplit=1)[0].strip("`'\" ")
            if c and c not in exec_cmds:
                exec_cmds.append(c)
        for cmd_clean in exec_cmds[:2]:
            print(f"\n[Executing] $ {cmd_clean}")
            try:
                subprocess.Popen(cmd_clean, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
            except Exception as ex:
                print(f"[Exec Error] {ex}")

        # Update history
        history.append({"role": "user", "content": query})
        history.append({"role": "assistant", "content": answer})
        save_session(history)
    except Exception as e:
        print(f"\n[Local Brain Offline] Falling back to default assistant: {e}")
        speak_sentence("I am standing by, Sir. The local Ollama engine is currently offline.")
        return 2

    pipeline.close()
    return 0

if __name__ == "__main__":
    sys.exit(main())
