import subprocess
import os
import sys


class LessPager:
    def run(self, path: str, config):
        os.environ["LESSSECURE"] = (
            str(config.get("less_lesssecure") or "1")
        )
        os.environ["TERM"] = (
            config.get("less_term") or "linux"
        )
        os.environ["LESS"] = (
            config.get("less_opts")
            or "--LONG-PROMPT --chop-long-lines --IGNORE-CASE "
            "--jump-target=10 --max-forw-scroll=100 --window=-4 "
            "--status-column"
        )
        if config.get("less_follow_name"):
            os.environ["LESS"] = \
                os.environ.get("LESS", "") + " --follow-name"
        lesskey = (
            config.get("less_lesskey")
            or "/usr/share/console-log/lesskey"
        )
        if os.path.exists(lesskey):
            os.environ["LESSKEY"] = lesskey
        try:
            subprocess.run(
                [
                    "less",
                    f"-Pw\"less {path}\"",
                    "+F",
                    path
                ],
                check=True,
            )
        except FileNotFoundError:
            print(
                "Error: 'less' command not found.",
                "Please make sure it is installed.",
                file=sys.stderr,
            )
        except subprocess.CalledProcessError as e:
            print(
                f"Error: 'less' exited with code {e.returncode}",
                file=sys.stderr,
            )
