from __future__ import annotations

import os
from logger import get_logger

log = get_logger("discovery.sftp")


def discover_sftp_users() -> list[dict]:
    """Discover SFTP users on the system by reading /etc/passwd."""
    if not os.path.exists("/etc/passwd"):
        log.debug("/etc/passwd not found, skipping SFTP discovery")
        return []

    users = []
    try:
        with open("/etc/passwd", "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith("#"):
                    continue
                parts = line.split(":")
                if len(parts) < 7:
                    continue
                
                username = parts[0]
                if not username.startswith("wolf_sftp_"):
                    continue
                
                passwd = parts[1]
                try:
                    uid = int(parts[2])
                except ValueError:
                    uid = None
                
                home_dir = parts[5]
                shell = parts[6]
                
                # Check if home directory exists/accessible
                home_exists = os.path.exists(home_dir)
                
                # Determine status
                if passwd.startswith("*") or passwd.startswith("!"):
                    status = "locked"
                elif shell in ("/usr/sbin/nologin", "/bin/false"):
                    status = "active"
                else:
                    status = "active"
                
                users.append({
                    "username": username,
                    "home_directory": home_dir,
                    "shell": shell,
                    "uid": uid,
                    "status": status,
                    "home_directory_exists": home_exists,
                    "category": "sftp_users"
                })
    except Exception as exc:
        log.warning("Failed to discover SFTP users: %s", exc)
        return []

    return users
