import json
from django.core.management.base import BaseCommand, CommandError
from django.db import DatabaseError
from django.db.migrations.exceptions import InconsistentMigrationHistory
from apps.configuration.readiness import inspect_installation, is_ready


class Command(BaseCommand):
    help="Read-only minimum intake setup checks; required failures exit nonzero. No provider calls or data creation."
    requires_system_checks=[]

    def add_arguments(self,parser):
        parser.add_argument("--json",action="store_true",help="Print structured, non-sensitive setup results.")

    def handle(self,*args,**options):
        try:
            checks=inspect_installation()
        except (DatabaseError,InconsistentMigrationHistory) as error:
            raise CommandError("Cannot inspect installation. Check database connectivity and migration consistency; no connection values are displayed.") from error
        ready=is_ready(checks)
        if options["json"]:
            self.stdout.write(json.dumps({"ready":ready,"checks":checks}))
        else:
            for row in checks:
                self.stdout.write(f'[{row["level"]}] {"PASS" if row["ready"] else "MISSING"}: {row["label"]}')
                if not row["ready"]:
                    self.stdout.write("  "+row["action"])
            self.stdout.write("MINIMUM INTAKE SETUP READY" if ready else "REQUIRED SETUP INCOMPLETE")
        if not ready:
            raise CommandError("Required installation setup is incomplete.")
