from abc import ABC, abstractmethod


class BaseStorage(ABC):
    """Abstract base for time-series storage backends.

    Default implementation uses Django ORM (works with PostgreSQL, SQLite, MySQL).
    Specialized backends (TimescaleDB, InfluxDB) override for performance at scale.
    """

    @abstractmethod
    def store_reading(self, reading_model, device, timestamp, data):
        """Store a sensor reading."""

    @abstractmethod
    def query_readings(
        self,
        reading_model,
        device=None,
        start=None,
        end=None,
        fields=None,
        limit=None,
        order="-timestamp",
    ):
        """Query stored readings with optional filters."""

    @abstractmethod
    def aggregate(
        self,
        reading_model,
        field,
        function="avg",
        device=None,
        start=None,
        end=None,
        interval=None,
    ):
        """Aggregate readings (avg, min, max, sum, count).

        If interval is provided, returns time-bucketed aggregation.
        """

    def downsample(
        self,
        reading_model,
        field,
        interval,
        function="avg",
        device=None,
        start=None,
        end=None,
    ):
        """Downsample time-series data to a lower resolution."""
        return self.aggregate(
            reading_model, field, function, device, start, end, interval
        )
