"""Host-system probes: systemd service status, USB mounts, upload sources."""

import os
import subprocess

import config


def service_status(service_name):
    """Check whether a systemd service is active."""
    try:
        result = subprocess.run(
            ["systemctl", "is-active", service_name],
            capture_output=True,
            text=True,
            timeout=5,
        )
        state = result.stdout.strip()
        return {"name": service_name, "active": state == "active", "state": state}
    except Exception as exc:
        return {"name": service_name, "active": False, "state": str(exc)}


def find_usb_mounts():
    """Return a list of mount-point paths that look like removable media."""
    mounts = []
    try:
        with open("/proc/mounts", "r") as fh:
            for line in fh:
                parts = line.split()
                if len(parts) >= 2:
                    mount_point = parts[1]
                    if mount_point.startswith(("/mnt/", "/media/")):
                        if os.path.isdir(mount_point):
                            mounts.append(mount_point)
    except OSError:
        pass
    return sorted(set(mounts))


def find_upload_sources():
    """Return sub-directories inside UPLOAD_DIR that look like image content."""
    sources = []
    if os.path.isdir(config.UPLOAD_DIR):
        try:
            entries = os.listdir(config.UPLOAD_DIR)
            if entries:
                sources.append(config.UPLOAD_DIR)
            for entry in entries:
                full = os.path.join(config.UPLOAD_DIR, entry)
                if os.path.isdir(full):
                    sources.append(full)
        except OSError:
            pass
    return sources
