"""Read-only minimum intake setup, not a production or full-workflow audit."""
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import connection
from django.db.migrations.executor import MigrationExecutor
from django.db.models import F, Q
from django.utils import timezone
from apps.access.scopes import assignment_is_valid
from apps.organization.models import Company, ServiceCenter, UserOrganizationAssignment
from apps.catalog.models import ProductModel
from apps.service_catalog.models import ComplaintSymptom, FaultDiagnosis, RepairAction, RootCause
from apps.parts.models import SparePart
from apps.inventory.models import InventoryLocation
from apps.frontdesk.models import AppointmentSlot
from apps.communications.models import NotificationTemplate
from apps.sla.models import SlaPolicy


def is_ready(checks):
    return bool(checks) and all(row["ready"] for row in checks if row["level"]=="REQUIRED")


def inspect_installation():
    checks=[]
    def add(code,level,ready,label,action):
        checks.append(dict(code=code,level=level,ready=bool(ready),label=label,action=action))
    executor=MigrationExecutor(connection)
    executor.loader.check_consistent_history(connection)
    migrated=not executor.loader.detect_conflicts() and not executor.migration_plan(executor.loader.graph.leaf_nodes())
    add("migrations","REQUIRED",migrated,"Migrations applied","Run python manage.py migrate with the intended deployment settings.")
    if not migrated:
        return checks
    companies=Company.objects.filter(is_active=True)
    centers=ServiceCenter.objects.filter(is_active=True,company__is_active=True,region__is_active=True,
        region__company_id=F("company_id"))
    add("company","REQUIRED",companies.exists(),"Active company","Create the real company in Organization Admin.")
    add("centers","REQUIRED",centers.exists() and not companies.exclude(pk__in=centers.values("company_id")).exists(),
        "Usable center for every active company","Create/activate a region and matching service center for each active company, parents first.")
    users=get_user_model().objects.filter(is_active=True).exclude(password="").exclude(password__startswith="!")
    add("administrator","REQUIRED",users.filter(is_staff=True,is_superuser=True).exists(),
        "Initial administrative login","Run createsuperuser interactively or restore an active staff superuser with a usable password.")
    models=ProductModel.objects.filter(is_active=True,brand__is_active=True,category__is_active=True,identification_policy__isnull=False)
    add("catalog","REQUIRED",models.exists(),"Registerable product model", "Configure an active brand, product category and model, then its explicit device identification policy.")
    assignments=UserOrganizationAssignment.objects.filter(assignment_is_valid()).filter(
        user__in=users.filter(is_superuser=False),role_assignments__is_active=True,role_assignments__user_id=F("user_id"),
        role_assignments__role__is_active=True,role_assignments__role__permissions__isnull=False)
    add("operators","RECOMMENDED",assignments.exists(),"Role-backed operational login",
        "Create non-superuser accounts, usable passwords, active organizational assignments and role assignments. Review exact workflow permissions separately.")
    active_models=ProductModel.objects.filter(is_active=True,brand__is_active=True,category__is_active=True)
    add("all_model_policies","RECOMMENDED",not active_models.filter(identification_policy=None).exists(),
        "All active models have identification policies","Configure missing policies; UNCONFIGURED is not an all-not-applicable policy.")
    for code,model,label,level in [("complaints",ComplaintSymptom,"Applicable complaint symptoms","RECOMMENDED"),
                                  ("diagnoses",FaultDiagnosis,"Applicable fault diagnoses","RECOMMENDED"),
                                  ("repair_actions",RepairAction,"Applicable repair actions","RECOMMENDED"),
                                  ("root_causes",RootCause,"Applicable known root causes","OPTIONAL")]:
        applicable=model.objects.filter(is_active=True).filter(Q(applies_to_all_product_categories=True)
            | Q(category_mappings__product_category_id__in=models.values("category_id")))
        add(code,level,models.exists() and applicable.exists(),label,
            "Configure real reference data and Product Category applicability in Service Configuration. RootCause may remain NULL; never fabricate unknown causes.")
    add("parts","OPTIONAL",SparePart.objects.filter(is_active=True,category__is_active=True).exists(),
        "Parts catalog","Configure actual part categories, parts and model/variant compatibility if parts operations are needed.")
    locations=InventoryLocation.objects.filter(is_active=True,company__in=companies).filter(
        Q(service_center=None) | Q(service_center__in=centers,company_id=F("service_center__company_id")))
    add("locations","OPTIONAL",locations.exists(),"Inventory locations","Configure inventory locations before receiving stock through supported inventory workflows.")
    today=timezone.localdate(timezone=timezone.get_default_timezone())
    add("slots","OPTIONAL",AppointmentSlot.objects.filter(is_active=True,service_center__in=centers,date__gte=today,capacity__gt=0).exists(),
        "Current/future appointment availability","Configure dated slots and capacity in Configuration Center if using appointments.")
    add("templates","OPTIONAL",NotificationTemplate.objects.filter(company__in=companies,is_active=True).exists(),
        "Notification templates","Configure company templates using supported placeholders; never store provider secrets in templates.")
    add("providers","OPTIONAL",any(getattr(settings,"COMMUNICATION_PROVIDERS",{}).values()),
        "Communication adapter configured (not delivery verified)","Configure a supported adapter and secrets through deployment configuration. No provider is invoked by this check.")
    policies=SlaPolicy.objects.filter(is_active=True,company__in=companies,effective_from__lte=today).filter(
        Q(effective_until=None)|Q(effective_until__gte=today)).filter(Q(service_center=None)|Q(service_center__in=centers,
        company_id=F("service_center__company_id"))).filter(Q(product_category=None)|Q(product_category__is_active=True))
    add("sla","OPTIONAL",policies.exists(),"Effective SLA policy","Configure an elapsed-time SLA policy and arrange explicit monitoring. This check does not assert coverage of every case.")
    return checks
