import json
import time
import os

class AuditLogger:
    def __init__(self, log_file):
        self.log_file = log_file
        # Ensure the directory containing the log file exists
        directory = os.path.dirname(os.path.abspath(self.log_file))
        if directory:
            os.makedirs(directory, exist_ok=True)

    def log_action(self, user, action, outcome):
        """
        Logs a user action to an append-only JSONL file.
        """
        log_entry = {
            "timestamp": time.time(),
            "user": user,
            "action": action,
            "outcome": outcome
        }
        with open(self.log_file, "a", encoding="utf-8") as f:
            f.write(json.dumps(log_entry) + "\n")

    def read_logs(self):
        """
        Helper method to read the logs (primarily for testing and auditing).
        """
        if not os.path.exists(self.log_file):
            return []
        with open(self.log_file, "r", encoding="utf-8") as f:
            return [json.loads(line) for line in f if line.strip()]
