import os
import time

from .api import poll_for_file, send_file_content


def read_file_safely(config, relative_path: str):
    """
    Secure file reader.
    Prevents directory traversal outside project root.
    """

    abs_path = os.path.realpath(
        os.path.join(config.root, relative_path)
    )

    # Prevent escaping project root
    if not abs_path.startswith(config.root):
        return None

    if not os.path.isfile(abs_path):
        return None

    try:
        with open(abs_path, "r", encoding="utf-8") as f:
            return f.read()
    except Exception:
        return None


def poll_and_send_files(config):
    """
    Continuously polls backend for requested files.
    """

    while True:
        try:
            file_path = poll_for_file(config)

            if file_path:
                content = read_file_safely(config, file_path)

                if content:
                    send_file_content(config, file_path, content)

        except Exception:
            # Never crash SDK
            pass

        time.sleep(2)