#!/usr/bin/env python3
"""
Worker health check and management utilities
"""
import psutil
import time
from typing import Optional, Tuple


def is_worker_running() -> Tuple[bool, Optional[int]]:
    """
    Check if background worker is running
    Returns: (is_running, pid)
    """
    for proc in psutil.process_iter(['pid', 'cmdline']):
        try:
            cmdline = proc.info.get('cmdline', [])
            if not cmdline:
                continue
            cmdline_str = ' '.join(str(arg) for arg in cmdline)
            # Check for Python-based worker (dev mode)
            if 'souleyez.engine.background' in cmdline_str and 'worker_loop' in cmdline_str:
                return True, proc.info['pid']
            # Check for binary-based worker (compiled mode)
            if 'souleyez' in cmdline_str and 'worker' in cmdline_str and 'start' in cmdline_str:
                return True, proc.info['pid']
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            continue
    return False, None


def start_worker_if_needed() -> bool:
    """
    Start worker if not running
    Returns: True if worker was started, False if already running
    """
    is_running, pid = is_worker_running()

    if is_running:
        return False

    # Start the worker
    from souleyez.engine.background import start_worker
    start_worker(detach=True)
    time.sleep(1)  # Give it a moment to start

    # Verify it started
    is_running, new_pid = is_worker_running()
    if is_running:
        return True
    else:
        raise RuntimeError("Failed to start background worker")


def stop_worker(pid: int) -> bool:
    """
    Stop the worker process
    """
    try:
        proc = psutil.Process(pid)
        proc.terminate()
        proc.wait(timeout=5)
        return True
    except (psutil.NoSuchProcess, psutil.TimeoutExpired):
        try:
            proc.kill()
            return True
        except BaseException:
            return False


def restart_worker() -> bool:
    """
    Restart the background worker
    Returns: True if successful
    """
    is_running, pid = is_worker_running()

    if is_running and pid:
        stop_worker(pid)
        time.sleep(1)

    return start_worker_if_needed()


def get_worker_status() -> dict:
    """
    Get comprehensive worker status
    """
    is_running, pid = is_worker_running()

    status = {
        'running': is_running,
        'pid': pid,
        'uptime': None,
        'cpu_percent': None,
        'memory_mb': None
    }

    if is_running and pid:
        try:
            proc = psutil.Process(pid)
            status['uptime'] = int(time.time() - proc.create_time())
            status['cpu_percent'] = proc.cpu_percent(interval=0.1)
            status['memory_mb'] = proc.memory_info().rss / 1024 / 1024
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            pass

    return status
