import os
import time

from .api import send_log


def detect_level(line: str) -> str:
    """
    Basic log level detection.
    """
    line_upper = line.upper()

    if "ERROR" in line_upper:
        return "ERROR"
    if "WARNING" in line_upper:
        return "WARNING"
    if "CRITICAL" in line_upper:
        return "CRITICAL"

    return "INFO"


def watch_logs(config):
    """
    Continuously watches log file and sends new lines to backend.
    """

    log_path = config.log_file

    while True:
        try:
            # Wait until log file exists
            if not os.path.exists(log_path):
                time.sleep(1)
                continue

            with open(log_path, "r", encoding="utf-8") as f:
                # Go to end of file
                f.seek(0, os.SEEK_END)

                while True:
                    line = f.readline()

                    if not line:
                        time.sleep(0.2)
                        continue

                    line = line.strip()
                    if not line:
                        continue

                    level = detect_level(line)
                    print("📤 Sending log:", line)
                    
                    send_log(config, level, line)

        except Exception:
            # Never crash SDK
            time.sleep(1)
            continue