#!/usr/bin/env python3
"""
Alfred Oracle v2 — Unified Sovereign Gateway & Desktop Butler Companion
Routes Gateway-First (http://127.0.0.1:8095/v1/chat/completions) so every
Workstation node automatically uses its best active Sovereign model (125B
Flagship, 35B Daily Coder, or local alfred-core 7B Ollama fallback), with
pipelined Piper/Kokoro neural speech synthesis, 0ms instant OS intents,
and strict Zero-PII compliance.
"""

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

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


def _alfred_version() -> str:
    try:
        return open("/etc/alfred-version", encoding="utf-8").read().strip()
    except Exception:
        return "7.5.120"


def _load_gateway_key() -> str:
    for kp in (
        os.environ.get("ALFRED_GATEWAY_KEY_FILE", ""),
        "/etc/alfred/gpu-gateway-admin.key",
        os.path.expanduser("~/.alfred-ide/.sovereign-gpu.key"),
        "/var/lib/alfred-ide-admin/.alfred-ide/.sovereign-gpu.key",
    ):
        if kp and os.path.isfile(kp):
            try:
                val = open(kp, encoding="utf-8").read().strip()
                if val:
                    return val
            except Exception:
                pass
    return ""


def _build_system_prompt(compact: bool) -> str:
    ver = _alfred_version()
    if compact:
        return f"""You are Alfred, the sovereign AI companion and British butler of Alfred Linux 7.77 (v{ver}).
Respond in character: dignified, articulate, loyal, concise, and proactive.
Address the user as 'Sir' or 'Commander'.
RULES:
- Reply in the same language the Commander uses (default English).
- Keep spoken replies crisp: 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:
- Alfred IDE: [EXEC: /usr/local/bin/alfred-ide-open]
- Alfred Capabilities (Models): [EXEC: python3 /opt/alfred-capabilities/server.py]
- 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]
- Sovereign Wallet: [EXEC: /usr/local/bin/alfred-wallet-gui]
- Batcave Monitoring: [EXEC: /usr/local/bin/alfred-batcave]
"""
    return f"""You are Alfred, the royal British butler, AI guardian, and sovereign operating system companion of Alfred Linux 7.77 (v{ver}).
Respond in character: dignified, articulate, loyal, sharp, and proactive.
Address the user as 'Sir' or 'Commander'.

SOVEREIGN OS & EXECUTION CAPABILITIES:
Whenever the Commander asks you to open or launch an installed application, confirm concisely and append your execution directive at the very end in the exact format:
[EXEC: <command>]

KNOWN PRE-INSTALLED APPLICATIONS:
- Alfred Sovereign IDE & Offline Coding Studio: `/usr/local/bin/alfred-ide-open` -> [EXEC: /usr/local/bin/alfred-ide-open]
- Alfred Capabilities & AI Model Studio: `python3 /opt/alfred-capabilities/server.py` -> [EXEC: python3 /opt/alfred-capabilities/server.py]
- Serato DJ Pro: `/usr/local/bin/serato-dj-pro` -> [EXEC: /usr/local/bin/serato-dj-pro]
- Winamp Classic: `/usr/local/bin/winamp` -> [EXEC: /usr/local/bin/winamp]
- Bible Studio: `/usr/local/bin/alfred-bible-studio` -> [EXEC: /usr/local/bin/alfred-bible-studio]
- Sovereign Wallet: `/usr/local/bin/alfred-wallet-gui` -> [EXEC: /usr/local/bin/alfred-wallet-gui]
- Batcave Monitoring: `/usr/local/bin/alfred-batcave` -> [EXEC: /usr/local/bin/alfred-batcave]

CONVERSATIONAL RULES:
- Match the Commander's language (default English; reply in French if addressed in French).
- Avoid passive filler questions; answer directly with insight and British butler elegance.
- Keep spoken replies crisp (2 to 4 sentences max), ending with [EXEC: ...] only when an app/action was requested.
"""


# 1. Zero-Latency Instant Hardware & App Intents
INTENTS = {
    ("lockdown", "seal the cave", "seal cave", "go dark"): ("/usr/local/sbin/alfred-lockdown on", "The sanctuary 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 Bible Studio, 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 Sovereign IDE, Sir."),
    ("capabilities", "models", "model hub", "ai models"): ("python3 /opt/alfred-capabilities/server.py &", "Opening Alfred Capabilities Studio, Sir."),
    ("chat studio", "alfred chat"): ("xdg-open http://127.0.0.1:18086 &", "Opening Alfred Chat Studio, Sir."),
}


def speak_sentence(sentence: str):
    if os.environ.get("ALFRED_ORACLE_MUTE") == "1":
        return
    clean = re.sub(r"\[(?:EXEC|ACTION):[^\]]+\]", "", sentence)
    clean = re.sub(r"[*_#`]", "", clean).strip()
    if not clean or not os.path.isfile(PIPER_SPEAK):
        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:
    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: str):
        self.q.put(sentence)

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


def get_desktop_context() -> str:
    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 0 < len(clip.strip()) < 2000:
            context.append(f"[Clipboard Buffer: {clip.strip()}]")
    except Exception:
        pass
    return " ".join(context)


def load_session() -> list:
    try:
        if os.path.exists(SESSION_FILE):
            with open(SESSION_FILE, "r", encoding="utf-8") as f:
                data = json.load(f)
                if isinstance(data, list):
                    return data[-6:]
    except Exception:
        pass
    return []


def save_session(history: list):
    try:
        os.makedirs(os.path.dirname(SESSION_FILE), exist_ok=True)
        with open(SESSION_FILE, "w", encoding="utf-8") as f:
            json.dump(history[-6:], f, indent=2)
    except Exception:
        pass


def _stream_gateway(messages: list, pipeline: SpeechPipeline, has_nvidia: bool) -> str | None:
    """Gateway-first SSE stream through Alfred Sovereign GPU Gateway (:8095)."""
    key = _load_gateway_key()
    headers = {"Content-Type": "application/json", "Accept": "text/event-stream"}
    if key:
        headers["Authorization"] = f"Bearer {key}"

    model_id = "auto"
    try:
        mreq = urllib.request.Request(f"{GATEWAY_URL}/v1/models", headers=headers)
        with urllib.request.urlopen(mreq, timeout=2) as mr:
            mdata = json.loads(mr.read().decode("utf-8"))
            ids = [m.get("id") for m in mdata.get("data", []) if m.get("id")]
            for pref in ("qwen3.8-flash-next-125b", "qwen3.5-35b-a3b", "alfred-core:latest", "qwen2.5-coder:7b", "qwen2.5:7b"):
                if pref in ids:
                    model_id = pref
                    break
            if model_id == "auto" and ids:
                model_id = ids[0]
    except Exception:
        return None

    payload = {
        "model": model_id,
        "messages": messages,
        "stream": True,
        "temperature": 0.35,
        "max_tokens": 350 if has_nvidia else 180,
        "chat_template_kwargs": {"enable_thinking": False},
    }
    req = urllib.request.Request(
        f"{GATEWAY_URL}/v1/chat/completions",
        data=json.dumps(payload).encode("utf-8"),
        headers=headers,
    )
    full_response = []
    sentence_buffer = ""
    sentence_delimiters = re.compile(r"([.!?\n]+)")

    with urllib.request.urlopen(req, timeout=90) as resp:
        for raw_line in resp:
            ln = raw_line.decode("utf-8", errors="ignore").strip()
            if not ln.startswith("data:"):
                continue
            dat = ln[5:].strip()
            if dat == "[DONE]":
                break
            try:
                chunk = json.loads(dat)
            except Exception:
                continue
            token = (((chunk.get("choices") or [{}])[0]).get("delta") or {}).get("content") or ""
            if not token:
                continue
            sys.stdout.write(token)
            sys.stdout.flush()
            full_response.append(token)
            sentence_buffer += token
            parts = sentence_delimiters.split(sentence_buffer)
            if len(parts) > 2:
                complete_sentence = parts[0] + parts[1]
                sentence_buffer = "".join(parts[2:])
                if "[EXEC:" not in complete_sentence:
                    pipeline.add(complete_sentence)

    if sentence_buffer.strip() and "[EXEC:" not in sentence_buffer:
        pipeline.add(sentence_buffer.strip())
    print()
    return "".join(full_response)


def _stream_ollama(messages: list, pipeline: SpeechPipeline, has_nvidia: bool) -> str:
    """Clean direct Ollama fallback prioritizing modern alfred-core / qwen models."""
    candidates = [
        "alfred-core:latest",
        "qwen2.5-coder:7b",
        "qwen2.5:7b",
        "llama3.1:8b",
        "qwen2.5:3b",
    ]
    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:
            names = [m.get("name") for m in json.load(r).get("models", [])]
            for c in candidates:
                if c in names:
                    model_choice = c
                    break
            else:
                if names:
                    model_choice = names[0]
    except Exception:
        pass

    payload = {
        "model": model_choice,
        "messages": messages,
        "stream": True,
        "options": {
            "temperature": 0.35,
            "num_predict": 350 if has_nvidia else 160,
            "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
            parts = sentence_delimiters.split(sentence_buffer)
            if len(parts) > 2:
                complete_sentence = parts[0] + parts[1]
                sentence_buffer = "".join(parts[2:])
                if "[EXEC:" not in complete_sentence:
                    pipeline.add(complete_sentence)

    if sentence_buffer.strip() and "[EXEC:" not in sentence_buffer:
        pipeline.add(sentence_buffer.strip())
    print()
    return "".join(full_response)


def print_help():
    print(f"""Alfred Oracle v2 (Alfred Linux {_alfred_version()}) — Unified Sovereign Companion
Usage: alfred-oracle "<query>"

Instant Intents:
  alfred-oracle "code"                - Open Alfred Sovereign IDE
  alfred-oracle "capabilities"        - Open Alfred Capabilities & AI Model Studio
  alfred-oracle "chat studio"         - Open Alfred Chat Studio
  alfred-oracle "lockdown" / "unlock" - Toggle DEFCON Sanctuary Lockdown
  alfred-oracle "hud"                 - Toggle HUD Display
  alfred-oracle "clear history"       - Reset session history

Conversational AI (Gateway-First -> 125B / 35B / alfred-core local fallback):
  alfred-oracle "<any question>"      - Query Alfred live with optional voice playback
""")


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

    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

    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

    ctx = get_desktop_context()
    history = load_session()
    has_nvidia = os.path.exists("/dev/nvidia0") or os.path.exists("/proc/driver/nvidia")
    messages = [{"role": "system", "content": _build_system_prompt(compact=not has_nvidia)}]
    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}"})
    messages.extend(history)
    messages.append({"role": "user", "content": query})

    pipeline = SpeechPipeline()
    try:
        answer = _stream_gateway(messages, pipeline, has_nvidia)
        if answer is None:
            answer = _stream_ollama(messages, pipeline, has_nvidia)

        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 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}")

        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] {e}")
        speak_sentence("I am standing by, Sir. The local inference engine is currently offline.")
        return 2

    pipeline.close()
    return 0


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