from django.core.management.base import BaseCommand, CommandError

from billing.models import Payment, Renewal
from clients.models import Client, ClientContact, ClientNote, ClientPortalAccess
from core.models import Document, PortalConfiguration, Provider
from domains.models import Domain
from hosting.models import HostingAccount
from imports.models import ImportBatch, ImportedObject, ImportRow
from notifications.models import EmailSuppression, NotificationAttempt, NotificationLog, NotificationTemplate
from operations.models import InternalTask
from monitoring.models import MonitorCheck, MonitorIncident, WebsiteMonitor
from services.models import Service
from support.models import SupportMessage, SupportTicket
from technical.models import (
    BackupRecord, DatabaseAsset, Server, SSLCertificate, TechnicalAsset,
    WordPressPlugin, WordPressSite, WordPressTheme,
)
from template_library.models import FormTemplate, FormTemplateField, ReusableTemplate, TemplateCategory, TemplateUsage
from websites.models import WebsiteProject


class Command(BaseCommand):
    help = "Audita se todos os módulos funcionais da demonstração têm dados para teste."

    def add_arguments(self, parser):
        parser.add_argument("--strict", action="store_true", help="Termina com erro se algum módulo estiver vazio.")

    def handle(self, *args, **options):
        models = [
            ("Configuração", PortalConfiguration),
            ("Fornecedores", Provider),
            ("Clientes", Client),
            ("Contactos", ClientContact),
            ("Notas", ClientNote),
            ("Acessos ao portal", ClientPortalAccess),
            ("Serviços", Service),
            ("Domínios", Domain),
            ("Alojamentos", HostingAccount),
            ("Projetos web", WebsiteProject),
            ("Renovações", Renewal),
            ("Pagamentos", Payment),
            ("Documentos", Document),
            ("Servidores", Server),
            ("Ativos técnicos", TechnicalAsset),
            ("Bases de dados", DatabaseAsset),
            ("Backups", BackupRecord),
            ("Sites WordPress", WordPressSite),
            ("Plugins WordPress", WordPressPlugin),
            ("Temas WordPress", WordPressTheme),
            ("Certificados SSL", SSLCertificate),
            ("Monitores de websites", WebsiteMonitor),
            ("Verificações de websites", MonitorCheck),
            ("Incidentes de monitorização", MonitorIncident),
            ("Tarefas", InternalTask),
            ("Tickets", SupportTicket),
            ("Mensagens de suporte", SupportMessage),
            ("Templates de email", NotificationTemplate),
            ("Notificações", NotificationLog),
            ("Tentativas de envio", NotificationAttempt),
            ("Emails bloqueados", EmailSuppression),
            ("Importações", ImportBatch),
            ("Linhas de importação", ImportRow),
            ("Registos importados", ImportedObject),
            ("Categorias de templates", TemplateCategory),
            ("Templates reutilizáveis", ReusableTemplate),
            ("Formulários", FormTemplate),
            ("Campos de formulários", FormTemplateField),
            ("Utilizações de templates", TemplateUsage),
        ]
        empty = []
        self.stdout.write("COBERTURA DOS DADOS DE DEMONSTRAÇÃO\n" + "=" * 42)
        for label, model in models:
            count = model.objects.count()
            marker = "OK" if count else "VAZIO"
            self.stdout.write(f"{marker:5} | {label:28} | {count:4}")
            if not count:
                empty.append(label)

        clients_without_services = Client.objects.filter(services__isnull=True).distinct()
        clients_without_access = Client.objects.filter(portal_accesses__isnull=True).distinct()
        self.stdout.write("\nREGRAS DE COBERTURA")
        self.stdout.write(f"Clientes sem serviços: {clients_without_services.count()}")
        self.stdout.write(f"Clientes sem credenciais: {clients_without_access.count()}")

        if clients_without_services.exists():
            empty.append("Clientes sem serviços")
        if clients_without_access.exists():
            empty.append("Clientes sem credenciais")

        if empty and options["strict"]:
            raise CommandError("Cobertura incompleta: " + ", ".join(empty))
        if empty:
            self.stdout.write(self.style.WARNING("Cobertura incompleta: " + ", ".join(empty)))
        else:
            self.stdout.write(self.style.SUCCESS("Todos os módulos funcionais têm dados fictícios para teste."))
