#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Fenrir TTY screen reader
# By Chrys, Storm Dragon, and contributors.

import getpass
import os
import string
import time
from select import select

from fenrirscreenreader.core import debug


def remove_nonprintable(text):
    # Get the difference of all ASCII characters from the set of printable
    # characters
    nonprintable = set([chr(i) for i in range(128)]).difference(
        string.printable
    )
    # Use translate to remove all non-printable characters
    return text.translate({ord(character): None for character in nonprintable})


def insert_newlines(string, every=64):
    return "\n".join(
        string[i : i + every] for i in range(0, len(string), every)
    )


def split_every(toSplit, every=64):
    return list(toSplit[i : i + every] for i in range(0, len(toSplit), every))


def create_screen_event_data(content):
    event_data = {
        "bytes": content,
        "lines": content["lines"],
        "columns": content["columns"],
        "textCursor": {
            "x": int(content["cursor"][0]),
            "y": int(content["cursor"][1]),
        },
        "screen": content["screen"],
        "text": content["text"],
        "attributes": content["attributes"],
        "screenUpdateTime": time.time(),
    }
    return event_data.copy()


def has_more(fd, timetout=0.05):
    r, _, _ = select([fd], [], [], timetout)
    return fd in r


def has_more_what(fd_list, timetout=0.05):
    if not isinstance(fd_list, list):
        return []
    elif fd_list == []:
        return []
    r, _, _ = select(fd_list, [], [], timetout)
    return r


def is_valid_shell(shell=""):
    if not isinstance(shell, str):
        return False
    if shell == "":
        return False
    try:
        if not os.path.isfile(shell):
            return False
        if not os.access(shell, os.X_OK):
            return False
    except Exception as e:
        # Utility function, no env access - use fallback logging
        print(
            f"screen_utils is_valid_shell: Error checking shell {shell}: {e}"
        )
        return False
    return True


def get_shell():
    try:
        shell = os.environ["FENRIRSHELL"]
        if is_valid_shell(shell):
            return shell
    except Exception as e:
        # Utility function, no env access - continue silently
        pass
    try:
        shell = os.environ["SHELL"]
        if is_valid_shell(shell):
            return shell
    except Exception as e:
        # Utility function, no env access - continue silently
        pass
    try:
        if os.access("/etc/passwd", os.R_OK):
            with open("/etc/passwd") as f:
                users = f.readlines()
                for user in users:
                    (username, encrypwd, uid, gid, gecos, homedir, shell) = (
                        user.split(":")
                    )
                    shell = shell.replace("\n", "")
                    if username == getpass.getuser():
                        if is_valid_shell(shell):
                            return shell
    except Exception as e:
        # Utility function, no env access - continue silently
        pass
    if is_valid_shell("/bin/bash"):
        return "/bin/bash"
    return "/bin/sh"
