"""Fleet metric time-series samples (Dashboard 24h trends)."""

from __future__ import annotations

from datetime import datetime, timedelta, timezone

from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession

from server.domain.models import FleetMetricSample
from server.utils.display_time import to_naive_utc

FLEET_METRIC_RETENTION_DAYS = 7
FLUSH_INTERVAL_MINUTES = 10


class FleetMetricRepositoryImpl:
    def __init__(self, session: AsyncSession):
        self.session = session

    async def insert_sample(
        self,
        *,
        recorded_at: datetime,
        online_count: int,
        sample_count: int,
        cpu_avg: int | None,
        mem_avg: int | None,
        disk_avg: int | None,
    ) -> FleetMetricSample:
        row = FleetMetricSample(
            recorded_at=to_naive_utc(recorded_at),
            online_count=online_count,
            sample_count=sample_count,
            cpu_avg=cpu_avg,
            mem_avg=mem_avg,
            disk_avg=disk_avg,
        )
        self.session.add(row)
        await self.session.flush()
        return row

    async def list_since(self, since_utc: datetime) -> list[FleetMetricSample]:
        since_naive = to_naive_utc(since_utc)
        result = await self.session.execute(
            select(FleetMetricSample)
            .where(FleetMetricSample.recorded_at >= since_naive)
            .order_by(FleetMetricSample.recorded_at.asc())
        )
        return list(result.scalars().all())

    async def purge_older_than(self, days: int = FLEET_METRIC_RETENTION_DAYS) -> int:
        cutoff = datetime.now(timezone.utc) - timedelta(days=days)
        cutoff_naive = to_naive_utc(cutoff)
        result = await self.session.execute(
            delete(FleetMetricSample).where(FleetMetricSample.recorded_at < cutoff_naive)
        )
        return int(result.rowcount or 0)
