"""Dashboard statistics assembled from durable records."""

from __future__ import annotations

from dataclasses import dataclass
from datetime import timedelta

from app.database.base import utcnow
from app.database.repositories import Repositories
from app.services.settings_service import SettingsService


@dataclass(frozen=True, slots=True)
class Dashboard:
    media_total: int
    posts_published: int
    posts_draft: int
    posts_failed: int
    posts_scheduled: int
    users_total: int
    users_active_week: int
    link_requests: int
    deliveries: int
    deleted_messages: int
    membership_checks: int
    expired_tokens: int
    destination_failures: int
    required_channels: int
    pending_jobs: int
    periods: dict[str, dict[str, int]]
    popular: list[tuple[int, str | None, int, int]]


class StatisticsService:
    def __init__(self, repos: Repositories, settings: SettingsService) -> None:
        self.repos = repos
        self.settings = settings

    async def dashboard(self) -> Dashboard:
        post_counts = await self.repos.stats.post_status_counts()
        return Dashboard(
            media_total=await self.repos.stats.media_count(),
            posts_published=post_counts.get("PUBLISHED", 0),
            posts_draft=post_counts.get("DRAFT", 0) + post_counts.get("READY", 0),
            posts_failed=post_counts.get("FAILED", 0),
            posts_scheduled=post_counts.get("SCHEDULED", 0),
            users_total=await self.repos.stats.user_count(),
            users_active_week=await self.repos.users.count_active_since(
                utcnow() - timedelta(days=7)
            ),
            link_requests=await self.repos.stats.link_request_count(),
            deliveries=await self.repos.stats.delivery_count(),
            deleted_messages=await self.repos.stats.deleted_delivery_count(),
            membership_checks=await self.repos.stats.membership_check_count(),
            expired_tokens=await self.repos.stats.expired_token_count(),
            destination_failures=await self.repos.stats.destination_failure_count(),
            required_channels=await self.repos.stats.required_channel_count(),
            pending_jobs=await self.repos.stats.pending_job_count(),
            periods=await self.repos.stats.period_counts(),
            popular=await self.repos.stats.popular_posts(5),
        )
