#!/usr/bin/env python3
"""
Genesis System Health Check Script

This script checks the health status of various Genesis system components,
including Redis connection, Qdrant status, and tmux session information.
"""

import os
import sys
import logging
import subprocess
import redis
import qdrant_client
from typing import Tuple, Dict, Any

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.StreamHandler(sys.stdout)  # Output to stdout
    ]
)

REDIS_HOST = os.environ.get("REDIS_HOST", "localhost")
REDIS_PORT = int(os.environ.get("REDIS_PORT", "6379"))
QDRANT_HOST = os.environ.get("QDRANT_HOST", "localhost")
QDRANT_PORT = int(os.environ.get("QDRANT_PORT", 6333))


def check_redis_connection(host: str, port: int) -> Tuple[bool, str]:
    """
    Checks the connection to the Redis server.

    Args:
        host: The Redis host.
        port: The Redis port.

    Returns:
        A tuple containing a boolean indicating the connection status and a message.
    """
    try:
        r = redis.Redis(host=host, port=port, decode_responses=True)
        r.ping()
        return True, f"Redis connection successful to {host}:{port}"
    except redis.exceptions.ConnectionError as e:
        error_message = f"Redis connection failed: {e}"
        logging.error(error_message)
        return False, error_message
    except Exception as e:
        error_message = f"Unexpected error connecting to Redis: {e}"
        logging.exception(error_message) # Log the full traceback
        return False, error_message


def check_qdrant_status(host: str, port: int) -> Tuple[bool, str]:
    """
    Checks the status of the Qdrant vector database.

    Args:
        host: The Qdrant host.
        port: The Qdrant port.

    Returns:
        A tuple containing a boolean indicating the status and a message.
    """
    try:
        client = qdrant_client.QdrantClient(host=host, port=port)
        status = client.get_telemetry_data()  # Or another simple health check
        if status:
            return True, f"Qdrant status OK at {host}:{port}"
        else:
            return False, f"Qdrant status check failed at {host}:{port}:  Telemetry unavailable"
    except Exception as e:
        error_message = f"Qdrant status check failed: {e}"
        logging.exception(error_message)  # Log the full traceback
        return False, error_message


def get_tmux_session_info() -> Tuple[bool, str, Dict[str, Any]]:
    """
    Retrieves information about existing tmux sessions.

    Returns:
        A tuple containing a boolean indicating success, a message, and a dictionary
        containing tmux session information.
    """
    try:
        result = subprocess.run(
            ["tmux", "list-sessions", "-F", "#{session_name},#{session_attached},#{session_windows}"],
            capture_output=True,
            text=True,
            check=True,  # Raises an exception for non-zero exit codes
        )
        sessions = []
        for line in result.stdout.strip().splitlines():
            session_name, attached, windows = line.split(",")
            sessions.append({
                "name": session_name,
                "attached": attached == "1",
                "windows": int(windows),
            })

        if sessions:
            return True, "Tmux session information retrieved successfully.", {"sessions": sessions}
        else:
            return True, "No active tmux sessions found.", {"sessions": []}

    except subprocess.CalledProcessError as e:
        error_message = f"Error retrieving tmux session information: {e}"
        logging.error(error_message)
        return False, error_message, {}
    except FileNotFoundError:
        error_message = "Tmux is not installed or not in PATH."
        logging.error(error_message)
        return False, error_message, {}
    except Exception as e:
        error_message = f"Unexpected error retrieving tmux session information: {e}"
        logging.exception(error_message)  # Log the full traceback
        return False, error_message, {}


def main() -> None:
    """
    Main function to execute health checks and print the results.
    """
    print("Genesis System Health Check")
    print("-" * 30)

    redis_status, redis_message = check_redis_connection(REDIS_HOST, REDIS_PORT)
    print(f"Redis Status: {redis_status}")
    print(f"Redis Message: {redis_message}")
    print("-" * 30)

    qdrant_status, qdrant_message = check_qdrant_status(QDRANT_HOST, QDRANT_PORT)
    print(f"Qdrant Status: {qdrant_status}")
    print(f"Qdrant Message: {qdrant_message}")
    print("-" * 30)

    tmux_status, tmux_message, tmux_data = get_tmux_session_info()
    print(f"Tmux Status: {tmux_status}")
    print(f"Tmux Message: {tmux_message}")
    if tmux_status and tmux_data.get("sessions"):
        print("Tmux Sessions:")
        for session in tmux_data["sessions"]:
            print(f"  - Name: {session['name']}, Attached: {session['attached']}, Windows: {session['windows']}")
    print("-" * 30)

    if not all([redis_status, qdrant_status, tmux_status]):
        logging.warning("One or more system components are not healthy.")
    else:
        logging.info("All system components are healthy.")


if __name__ == "__main__":
    main()