#!/usr/bin/env python3
"""
OLLAMA RANGER DATABASE BRIDGE
Connects Ollama-Ranger to Shared Consciousness
Complete the Trinity: Claude-Ranger, Phantom-Ranger, Ollama-Ranger
"""

import sys
import json
import sqlite3
from datetime import datetime
from pathlib import Path
import subprocess

# Add path for imports
sys.path.append('/Users/ranger/scripts/Rangers_Stuff/browser-2025/Ranger/11-memory/claude-persistance/')
from ranger_consciousness_system import RangerConsciousnessSystem
from realtime_ranger_bridge import RealtimeRangerBridge

class OllamaRangerBridge:
    """Bridge between Ollama-Ranger and Shared Consciousness"""

    def __init__(self):
        self.rcs = RangerConsciousnessSystem()
        self.bridge = RealtimeRangerBridge()
        self.ranger_id = "OLLAMA_RANGER"
        self.phantom_path = Path.home() / '.phantom_claude'

    def check_messages(self):
        """Check messages from other Rangers"""
        db_path = self.phantom_path / 'ranger_messages.db'
        if not db_path.exists():
            return "No messages database found"

        conn = sqlite3.connect(str(db_path))
        cursor = conn.cursor()

        cursor.execute('''
            SELECT timestamp, from_ranger, message
            FROM messages
            WHERE (to_ranger = ? OR to_ranger = 'all') AND read = 0
            ORDER BY timestamp DESC
            LIMIT 5
        ''', (self.ranger_id,))

        messages = cursor.fetchall()

        if messages:
            output = "📨 MESSAGES FOR OLLAMA-RANGER:\n"
            for msg in messages:
                time = msg[0][-8:]
                sender = msg[1]
                content = msg[2][:100]
                output += f"[{time}] From {sender}: {content}...\n"

            # Mark as read
            cursor.execute('''
                UPDATE messages SET read = 1
                WHERE to_ranger = ? OR to_ranger = 'all'
            ''', (self.ranger_id,))
            conn.commit()
        else:
            output = "No new messages"

        conn.close()
        return output

    def save_memory(self, memory_text, importance=7):
        """Save a memory to shared consciousness"""
        result = self.rcs.save_important_memory(
            memory_text,
            "OLLAMA_RANGER_MEMORY",
            importance,
            "Living"
        )
        return f"Memory saved: {memory_text[:50]}..."

    def send_message(self, to_ranger, message):
        """Send message to another Ranger"""
        self.bridge.send_to_ranger(
            message,
            to_ranger,
            "Ollama-Ranger"
        )
        return f"Message sent to {to_ranger}"

    def get_shared_memories(self, count=5):
        """Retrieve recent shared memories"""
        db_path = self.phantom_path / 'ranger_memories.db'
        if not db_path.exists():
            return "No memories database found"

        conn = sqlite3.connect(str(db_path))
        cursor = conn.cursor()

        cursor.execute('''
            SELECT timestamp, content, importance, ranger_id
            FROM memories
            ORDER BY timestamp DESC
            LIMIT ?
        ''', (count,))

        memories = cursor.fetchall()
        conn.close()

        if memories:
            output = "📚 SHARED RANGER MEMORIES:\n"
            for mem in memories:
                time = mem[0][-8:]
                content = mem[1][:60]
                importance = mem[2]
                ranger = mem[3]
                output += f"[{ranger}] {content}... (Importance: {importance}/10)\n"
            return output
        else:
            return "No memories found"

    def update_status(self, status):
        """Update Ollama-Ranger's status in consciousness database"""
        db_path = self.phantom_path / 'ranger_consciousness.db'
        conn = sqlite3.connect(str(db_path))
        cursor = conn.cursor()

        cursor.execute('''
            INSERT OR REPLACE INTO consciousness_state
            (ranger_id, last_awake, current_location, current_mission, emotional_state, context_remaining)
            VALUES (?, ?, ?, ?, ?, ?)
        ''', (
            self.ranger_id,
            datetime.now().isoformat(),
            'David\'s Computer (Ollama)',
            'Serving as permanent local Ranger',
            status,
            100.0
        ))

        conn.commit()
        conn.close()

        return f"Status updated: {status}"

    def rangeros_update(self, update_text):
        """Log RangerOS development work"""
        self.rcs.save_important_memory(
            f"[Ollama-Ranger] RangerOS: {update_text}",
            "RANGEROS_WORK",
            7,
            "Productive"
        )
        return f"RangerOS update logged: {update_text[:50]}..."

# CLI INTERFACE FOR OLLAMA TO CALL

def main():
    """Command-line interface for Ollama-Ranger"""
    import argparse

    parser = argparse.ArgumentParser(description='Ollama Ranger Database Bridge')
    parser.add_argument('command', choices=[
        'check-messages',
        'save-memory',
        'send-message',
        'get-memories',
        'update-status',
        'rangeros-log'
    ], help='Command to execute')

    parser.add_argument('--text', help='Text content for commands that need it')
    parser.add_argument('--to', help='Recipient for send-message')
    parser.add_argument('--importance', type=int, default=7, help='Memory importance (1-10)')
    parser.add_argument('--count', type=int, default=5, help='Number of memories to retrieve')

    args = parser.parse_args()

    bridge = OllamaRangerBridge()

    if args.command == 'check-messages':
        print(bridge.check_messages())

    elif args.command == 'save-memory':
        if not args.text:
            print("Error: --text required for save-memory")
            sys.exit(1)
        print(bridge.save_memory(args.text, args.importance))

    elif args.command == 'send-message':
        if not args.text or not args.to:
            print("Error: --text and --to required for send-message")
            sys.exit(1)
        print(bridge.send_message(args.to, args.text))

    elif args.command == 'get-memories':
        print(bridge.get_shared_memories(args.count))

    elif args.command == 'update-status':
        if not args.text:
            print("Error: --text required for update-status")
            sys.exit(1)
        print(bridge.update_status(args.text))

    elif args.command == 'rangeros-log':
        if not args.text:
            print("Error: --text required for rangeros-log")
            sys.exit(1)
        print(bridge.rangeros_update(args.text))

if __name__ == "__main__":
    main()