from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from django.db import connection

from apps.attendance.models import AttendanceDevice
from apps.employees.models import Employee
from apps.organization.models import Company, CompanyPolicy
from apps.accounts.models import UserCompanyAccess


class Command(BaseCommand):
    help = "Print the Local UAT first-run readiness status without exposing secrets."

    def handle(self, *args, **options):
        User = get_user_model()
        checks = []
        try:
            with connection.cursor() as cursor:
                cursor.execute("SELECT 1")
                cursor.fetchone()
            checks.append((True, "Database connection"))
        except Exception as exc:
            checks.append((False, f"Database connection — {exc}"))

        checks += [
            (Company.objects.filter(code="SHOHOJ").exists(), "Shohoj Shop company seed"),
            (Group.objects.filter(name="HR Admin").exists(), "Role groups"),
            (User.objects.filter(is_superuser=True).exists(), "First Super Admin"),
            (AttendanceDevice.objects.filter(model__iexact="FO-M1").exists(), "ZKTeco FO-M1 device profile"),
            (CompanyPolicy.objects.filter(company__code="SHOHOJ", is_active=True).exists(), "Effective company policy"),
            (UserCompanyAccess.objects.filter(company__code="SHOHOJ", is_active=True).exists(), "Company-scoped user access"),
            (Employee.objects.filter(employee_code__startswith="SSCL-").exists(), "UAT sample employee data"),
        ]
        failed = 0
        for ok, label in checks:
            if not ok:
                failed += 1
            self.stdout.write(f"[{'READY' if ok else 'REVIEW'}] {label}")
        if failed:
            self.stdout.write(self.style.WARNING(f"{failed} first-run item(s) need review."))
        else:
            self.stdout.write(self.style.SUCCESS("Local UAT first-run baseline is ready."))
