"""Helpdesk monitoring configuration.

Provides health-check endpoints and operational alerts configuration
for production monitoring of the helpdesk module.

Usage:
    Import ``check_health`` from your monitoring framework (e.g. django-health-check)
    or call directly from a management command / readiness probe.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any

import structlog

_log = structlog.get_logger("simorgh.helpdesk.monitoring")


# ---------------------------------------------------------------------------
# Health check
# ---------------------------------------------------------------------------


@dataclass
class HealthStatus:
    healthy: bool = True
    checks: dict[str, bool] = field(default_factory=dict)
    details: dict[str, Any] = field(default_factory=dict)


def check_health(tenant_id: int | None = None) -> HealthStatus:
    """Run all helpdesk health checks.

    Parameters
    ----------
    tenant_id:
        If provided, run tenant-specific checks (queue connectivity, SLA timer
        backlog). If None, run only global checks.

    Returns
    -------
    HealthStatus with per-check results and overall healthy flag.
    """
    status = HealthStatus()

    # 1. Database connectivity — can we query tickets?
    try:
        from simorgh.apps.helpdesk.models import Ticket
        count = Ticket.objects.count()
        status.checks["db_connectivity"] = True
        status.details["ticket_count"] = count
    except Exception as exc:
        status.healthy = False
        status.checks["db_connectivity"] = False
        status.details["db_error"] = str(exc)
        _log.error("helpdesk.health.db_connectivity.failed", error=str(exc))

    # 2. SLA timer backlog — are there overdue, unresolved timers?
    try:
        from django.utils import timezone
        from simorgh.apps.helpdesk.models import SLATimer

        overdue = SLATimer.objects.filter(
            due_at__lt=timezone.now(),
            is_resolved=False,
            is_deleted=False,
        ).count()
        status.checks["sla_backlog"] = True
        status.details["overdue_sla_timers"] = overdue
        if overdue > 1000:
            _log.warning(
                "helpdesk.health.sla_backlog.high",
                overdue_count=overdue,
            )
    except Exception as exc:
        status.checks["sla_backlog"] = False
        status.details["sla_error"] = str(exc)
        _log.error("helpdesk.health.sla_backlog.failed", error=str(exc))

    # 3. Tenant-specific: queue configuration
    if tenant_id is not None:
        try:
            from simorgh.apps.helpdesk.models import Queue
            active_queues = Queue.objects.filter(
                tenant_id=tenant_id,
                is_active=True,
                is_deleted=False,
            ).count()
            status.checks["tenant_active_queues"] = True
            status.details["active_queues"] = active_queues
            if active_queues == 0:
                _log.warning(
                    "helpdesk.health.no_active_queues",
                    tenant_id=tenant_id,
                )
        except Exception as exc:
            status.checks["tenant_active_queues"] = False
            status.details["tenant_queue_error"] = str(exc)

    return status


# ---------------------------------------------------------------------------
# Alert thresholds
# ---------------------------------------------------------------------------

# Recommended alerting rules for external monitoring system (Prometheus, Grafana, etc.):

ALERT_RULES: dict[str, dict[str, Any]] = {
    "helpdesk_sla_breach_rate": {
        "description": "SLA breach rate exceeds 5% over trailing 1h window.",
        "severity": "warning",
        "threshold": 0.05,
        "window": "1h",
        "query": 'rate(helpdesk_sla_breached_total[1h]) / rate(helpdesk_ticket_created_total[1h]) > 0.05',
    },
    "helpdesk_ticket_backlog": {
        "description": "Open tickets exceed 500 per tenant.",
        "severity": "warning",
        "threshold": 500,
        "query": 'helpdesk_open_tickets > 500',
    },
    "helpdesk_automation_failure_rate": {
        "description": "Automation execution failure rate exceeds 10% over 10m window.",
        "severity": "critical",
        "threshold": 0.10,
        "window": "10m",
        "query": 'rate(helpdesk_automation_error_total[10m]) / rate(helpdesk_automation_fired_total[10m]) > 0.10',
    },
    "helpdesk_api_error_rate": {
        "description": "API 5xx error rate exceeds 1% over 5m window.",
        "severity": "critical",
        "threshold": 0.01,
        "window": "5m",
        "query": 'rate(helpdesk_api_5xx_total[5m]) / rate(helpdesk_api_requests_total[5m]) > 0.01',
    },
    "helpdesk_ai_action_failure_rate": {
        "description": "AI action execution failure rate exceeds 20% over 15m window.",
        "severity": "warning",
        "threshold": 0.20,
        "window": "15m",
        "query": 'rate(helpdesk_ai_action_error_total[15m]) / rate(helpdesk_ai_action_total[15m]) > 0.20',
    },
}

# ---------------------------------------------------------------------------
# Production readiness checklist
# ---------------------------------------------------------------------------

PRODUCTION_CHECKLIST: list[str] = [
    "☐ Database connection pooling configured (pgbouncer or Django CONN_MAX_AGE)",
    "☐ Celery worker running for SLA breach checks and auto-close tasks",
    "☐ Celery beat scheduler configured for periodic tasks",
    "☐ Redis/RabbitMQ configured as Celery broker (not Django DB)",
    "☐ structlog configured with JSON renderer for production log aggregation",
    "☐ Sentry (or equivalent) configured for error tracking",
    "☐ SSL/TLS enforced on all API endpoints",
    "☐ X-Tenant header validated by middleware on every request",
    "☐ File upload size limits configured at reverse proxy (nginx/caddy) layer",
    "☐ Database backups scheduled (daily minimum)",
    "☐ AI provider API keys stored in environment variables or secrets manager",
    "☐ Rate limiting configured at API gateway or middleware layer",
    "☐ Health check endpoint exposed at /health/helpdesk/",
]

