import logging
from pathlib import Path

from test_automation_suite.core.config import Config
from test_automation_suite.templates import render_and_write_template
from test_automation_suite.utility.cmd import run_cmd_t

logger = logging.getLogger(__name__)


def detect_display_manager() -> str:
    """Detect the active display manager using systemd or running processes."""
    stdout, _stderr = run_cmd_t("systemctl show -p ExecStart display-manager.service")
    if stdout and "=" in stdout:
        path = stdout.split("=", 1)[1].strip()
        dm = Path(path).name
        logger.info("Detected display manager via systemd: %s", dm)
        return dm

    # Fallback: check running processes
    for dm_candidate in ["gdm", "gdm3", "lightdm", "sddm"]:
        out, _ = run_cmd_t(f"pgrep -x {dm_candidate}")
        if out:
            logger.info("Detected display manager via process: %s", dm_candidate)
            return dm_candidate

    logger.warning("Could not detect display manager")
    return ""


def enable_autologin(username: str = "test") -> None:
    """Enable autologin for the given user on the detected display manager."""
    dm = detect_display_manager()
    if not dm:
        logger.error("No display manager detected. Cannot enable autologin.")
        return

    try:
        if dm in ["gdm", "gdm3"]:
            conf_file = Path("/etc/gdm/custom.conf")
            conf_file.parent.mkdir(parents=True, exist_ok=True)
            conf_file.write_text(
                f"[daemon]\nAutomaticLoginEnable=True\nAutomaticLogin={username}\n",
            )
            logger.info("Autologin enabled in %s", conf_file)

        elif dm == "lightdm":
            conf_dir = Path("/etc/lightdm/lightdm.conf.d")
            conf_dir.mkdir(parents=True, exist_ok=True)
            conf_file = conf_dir / "50-autologin.conf"
            conf_file.write_text(f"[Seat:*]\nautologin-user={username}\nautologin-user-timeout=0\n")
            logger.info("Autologin enabled in %s", conf_file)

        elif dm == "sddm":
            conf_dir = Path("/etc/sddm.conf.d")
            conf_dir.mkdir(parents=True, exist_ok=True)
            conf_file = conf_dir / "autologin.conf"
            conf_file.write_text(f"[Autologin]\nUser={username}\nSession=plasma.desktop\n")
            logger.info("Autologin enabled in %s", conf_file)

        else:
            logger.warning("Unsupported display manager: %s", dm)
            return

        # Restart display manager
        _out, err = run_cmd_t(f"systemctl restart {dm}")
        if err:
            logger.warning("Error restarting %s: %s", dm, err)
        else:
            logger.info("%s restarted to apply autologin", dm)

    except PermissionError:
        logger.exception("Permission denied: run as root")
    except Exception:
        logger.exception("Failed to enable autologin")


def create_autostart_file() -> bool:
    """
    Generate the autostart.desktop file for the user
    """

    autostart_dir = Path("/home/test/.config/autostart")
    output_file = autostart_dir / "tas-autostarter.desktop"

    autostart_dir.mkdir(parents=True, exist_ok=True)
    success = render_and_write_template("autostart.desktop", output_file, {})
    if not success:
        logger.fatal("Failed to create autostart file at %s", output_file)
    return success


def _remove_file(file_path: Path, description: str) -> None:
    """Helper function to remove a file with error handling."""
    if file_path.exists():
        try:
            file_path.unlink()
            logger.info("Removed %s: %s", description, file_path)
        except PermissionError:
            logger.exception("Permission denied when removing %s", file_path)
        except Exception:
            logger.exception("Failed to remove %s", file_path)
    else:
        logger.debug("%s does not exist: %s", description, file_path)


def cleanup(config: Config) -> None:
    """
    Remove persistence file, autostart file and undo autologin for the user.
    """
    _remove_file(config.state_file, "persistence file")
    _remove_file(config.autostart_file, "autostart file")

    display_managers = {
        "gdm": Path("/etc/gdm/custom.conf"),
        "gdm3": Path("/etc/gdm/custom.conf"),
        "lightdm": Path("/etc/lightdm/lightdm.conf.d/50-autologin.conf"),
        "sddm": Path("/etc/sddm.conf.d/autologin.conf"),
    }

    for dm, conf_file in display_managers.items():
        if conf_file.exists():
            try:
                if dm == "lxdm":
                    # Remove autologin line only
                    lines = conf_file.read_text().splitlines()
                    new_lines = [line for line in lines if not line.startswith("autologin=")]
                    conf_file.write_text("\n".join(new_lines) + "\n")
                    logger.info("Removed autologin line from %s", conf_file)
                else:
                    conf_file.unlink()
                    logger.info("Removed autologin config file: %s", conf_file)
            except PermissionError:
                logger.exception("Permission denied when modifying %s", conf_file)
            except Exception:
                logger.exception("Failed to remove autologin config %s", conf_file)
        else:
            logger.debug("Autologin config does not exist for %s: %s", dm, conf_file)
