"""
ReportController handles various reporting functionalities for the OTT platform.
It provides endpoints to fetch channel access code redemption counts, content ingestion summaries,
user engagement summaries, and more. The controller interacts with multiple databases including MongoDB,
MySQL, and Cassandra to gather and aggregate data efficiently.
"""

from flask import current_app
from app.utils.helpers import get_logger, performance_log
from app.controllers.base_controller import BaseController
from app.models.mysql_model import MySQLModel


class ReportController(BaseController):
    """
    Report controller with PHP trait-like API response functionality.
    Inherits from BaseController to get direct access to response methods like PHP traits.
    """

    def __init__(self):
        super().__init__()
        self.mysql = MySQLModel()
        self.logger = get_logger("report_controller")

    @performance_log
    def get_channel_access_code_redeem_count(self, validated_query):
        """
        Fetch the count of users who have redeemed channel access codes.
        Note: Caching is handled at the route level for better efficiency.

        Args:
            validated_query: Validated ActiveUsersRequest instance

        Returns:
            API response with user count or error
        """

    def get_database_health(self) -> tuple:
        """
        Check health status of all databases.

        Returns:
            API response with database health status
        """
        try:
            self.logger.info("Checking database health status")

            health_status = {
                "mysql": self.mysql.test_connection(),
                "overall_status": "healthy",
            }

            # Check if any database is down
            failed_databases = []
            for db_name, status in health_status.items():
                if db_name != "overall_status" and isinstance(status, dict):
                    if status.get("status") != "connected":
                        failed_databases.append(db_name)

            if failed_databases:
                health_status["overall_status"] = "degraded"
                health_status["failed_databases"] = failed_databases

                return self.service_unavailable(health_status)

            return self.ok(health_status)

        except Exception as e:
            self.logger.error(
                f"Error checking database health: {str(e)}", exc_info=True
            )
            return self.server_error(
                {
                    "message": "Failed to check database health",
                    "error_type": type(e).__name__,
                }
            )
