#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
// PURPOSE: Grok Bridge for PULSE Brain.
// [Phase 2: Multi-Agent Orchestration]
"""

import sys
import os
from datetime import datetime, timezone
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR.parent.parent

# When run directly, ensure pulse package is importable
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

from pulse.core.pulse_crypto import PulseCrypto
from pulse.core.brain_utils import load_config
from pulse.core.paths import get_state_dir

STATE_DIR = get_state_dir()
LOG_FILE = STATE_DIR / "pulse_captured_grok.log"


def _format_log_entry(ts_iso, role, text):
    """Format a log entry matching the bridge-readable format."""
    try:
        if isinstance(ts_iso, str):
            dt = datetime.fromisoformat(ts_iso.replace("Z", "+00:00"))
        else:
            dt = datetime.now(timezone.utc)
        ts_str = dt.strftime("%Y-%m-%d %H:%M:%S")
    except Exception:
        ts_str = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
    return f"[{ts_str}] {role}: {text}"


class PulseGrok:
    """
    // The Grok Agent Bridge.
    // Handles context injection and evidence capture for xAI models.
    """

    def __init__(self):
        self.crypto = PulseCrypto()
        self.config = load_config()

    def sync(self, domain: str, evidence_text: str):
        """// Captures evidence from a Grok interaction and signs it."""
        try:
            ts = datetime.now(timezone.utc).isoformat()
            content_part = _format_log_entry(ts, "GROK", f"[{domain}] {evidence_text}")
            try:
                signature = self.crypto.sign_string(content_part, "grok_daemon")
                line = content_part + " | SIG: " + signature + "\n"
            except Exception:
                line = content_part + "\n"
            LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
            with open(LOG_FILE, "a", encoding="utf-8") as f:
                f.write(line)
            print(f"  [GROK_SYNC] Evidence captured and signed in {domain}")
        except Exception as e:
            print(f"  [GROK_ERROR] Failed to capture evidence: {e}")

if __name__ == "__main__":
    # Example usage for manual sync
    grok = PulseGrok()
    if len(sys.argv) > 2:
        grok.sync(sys.argv[1], sys.argv[2])
    else:
        print("Usage: python pulse_grok.py <domain> <evidence_text>")
