"""Local event buffer for offline resilience."""

import logging
import sys
import json
import time
from pathlib import Path
from typing import List, Dict, Any, Optional
from threading import Lock

logger = logging.getLogger(__name__)


BUFFER_DIR = Path("/var/lib/runsentry/buffer")
BUFFER_DIR.mkdir(parents=True, exist_ok=True)


class EventBuffer:
    """Thread-safe event buffer for offline resilience."""

    def __init__(self, max_events: int = 10000):
        self.max_events = max_events
        self.lock = Lock()

    def _get_buffer_file(self) -> Path:
        """Get the buffer file path."""
        return BUFFER_DIR / "events.jsonl"

    def add(self, event: Dict[str, Any]):
        """Add an event to the buffer."""
        event["_buffered_at"] = time.time()
        event["_event_id"] = f"{int(time.time() * 1000000)}"

        with self.lock:
            buffer_file = self._get_buffer_file()
            try:
                with open(buffer_file, "a") as f:
                    f.write(json.dumps(event) + "\n")
            except Exception as e:
                logger.warning(f"Failed to buffer event: {e}")

    def get_pending(self, limit: int = 100) -> List[Dict[str, Any]]:
        """Get pending events from buffer."""
        with self.lock:
            buffer_file = self._get_buffer_file()
            if not buffer_file.exists():
                return []

            events = []
            remaining_lines = []

            try:
                with open(buffer_file, "r") as f:
                    for line in f:
                        if len(events) < limit:
                            try:
                                event = json.loads(line.strip())
                                events.append(event)
                            except json.JSONDecodeError:
                                continue
                        else:
                            remaining_lines.append(line)

                # Rewrite file with remaining events
                if remaining_lines:
                    with open(buffer_file, "w") as f:
                        f.writelines(remaining_lines)
                else:
                    buffer_file.unlink()

            except Exception as e:
                logger.warning(f"Failed to read buffer: {e}")

            return events

    def clear(self):
        """Clear all buffered events."""
        with self.lock:
            buffer_file = self._get_buffer_file()
            if buffer_file.exists():
                buffer_file.unlink()

