from getpass import getpass
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand, CommandError
from django.db import IntegrityError
from apps.configuration.demo import require_development, seed_demo, USERNAME


class Command(BaseCommand):
    help="Opt-in LOCAL DEVELOPMENT demo records. No default password, stock posting, financial transactions or message dispatch."
    requires_system_checks=[]

    def add_arguments(self,parser):
        parser.add_argument("--confirm-development",action="store_true",help="Confirm this is a disposable local development/test database, never production.")
        parser.add_argument("--set-password",action="store_true",help="Interactively set/reset only the non-staff demo operator password; never pass passwords as arguments.")

    def handle(self,*args,**options):
        if not options["confirm_development"]:
            raise CommandError("Use --confirm-development only for a disposable local development/test database.")
        try:
            require_development()
        except ValidationError as error:
            raise CommandError(" ".join(error.messages)) from error
        password=None
        if options["set_password"]:
            try:
                password=getpass("Development demo operator password: ")
                confirmation=getpass("Confirm password: ")
            except (EOFError,KeyboardInterrupt) as error:
                raise CommandError("Password entry cancelled; nothing was changed.") from error
            if not password or password!=confirmation:
                raise CommandError("Passwords must be nonblank and match; nothing was changed.")
        try:
            result=seed_demo(password=password)
        except (ValidationError,IntegrityError) as error:
            raise CommandError("Demo setup rejected: invalid configuration, password policy or reserved-record conflict. No seed changes were committed; never overwrite existing records to force seeding.") from error
        self.stdout.write("Demo configuration "+("created" if result["initial"] else "verified; existing history preserved")+".")
        self.stdout.write("Non-staff demo operator: "+USERNAME)
        self.stdout.write("Login enabled with your supplied password." if password else "No password was changed. New accounts have unusable passwords; use --set-password for an explicit development login.")
        self.stdout.write("No superuser, stock, invoice, payment or outbound message was created. Production setup uses real data and createsuperuser separately.")
