# retoor <retoor@molodetz.nl>

import logging

from devplacepy.services.base import BaseService, ConfigField
from devplacepy.services.moderation import deletion, queue, sla
from devplacepy.services.moderation.deletion import DEFAULT_GRACE_HOURS
from devplacepy.services.moderation.sla import DEFAULT_SLA_HOURS

logger = logging.getLogger(__name__)


class ModerationService(BaseService):
    title = "Moderation housekeeping"
    description = (
        "Purges deleted accounts once their grace window closes and reports the "
        "moderation queue's service-level snapshot."
    )
    default_enabled = True
    min_interval = 300
    METRICS_SECONDS = 60
    config_fields = [
        ConfigField(
            "moderation_sla_hours",
            "Response window (hours)",
            type="int",
            default=DEFAULT_SLA_HOURS,
            minimum=1,
            help=(
                "The published commitment. The admin queue badge turns red once the "
                "oldest open report is older than this."
            ),
            group="General",
        ),
        ConfigField(
            "account_deletion_grace_hours",
            "Account deletion grace (hours)",
            type="int",
            default=DEFAULT_GRACE_HOURS,
            minimum=0,
            help=(
                "How long a deleted account stays restorable before it is purged. "
                "The account is anonymised immediately either way."
            ),
            group="General",
        ),
    ]

    def __init__(self) -> None:
        super().__init__("moderation", interval_seconds=3600)

    async def run_once(self) -> None:
        purged = deletion.purge_due()
        if purged:
            self.log(f"Purged {purged} deleted account(s) past the grace window")
        snapshot = sla.snapshot()
        if snapshot["breached"]:
            self.log(
                f"{snapshot['breached']} report(s) past the "
                f"{snapshot['sla_hours']}h response window; "
                f"oldest open is {snapshot['oldest_open_hours']}h"
            )

    def collect_metrics(self) -> dict:
        snapshot = sla.snapshot()
        counts = queue.status_counts()
        return {
            "stats": [
                {"label": "Open reports", "value": counts.get("open", 0)},
                {"label": "Acknowledged", "value": counts.get("acknowledged", 0)},
                {"label": "Actioned", "value": counts.get("actioned", 0)},
                {"label": "Dismissed", "value": counts.get("dismissed", 0)},
                {"label": "Oldest open (h)", "value": snapshot["oldest_open_hours"]},
                {"label": "Response window (h)", "value": snapshot["sla_hours"]},
                {"label": "Past window", "value": snapshot["breached"]},
                {"label": "Pending purges", "value": len(deletion.due_purges())},
            ]
        }
