"""
management command: backfill_binary_tree

Rebuilds the company-managed binary tree from DistributorID global order.

Usage:
    python manage.py backfill_binary_tree
    python manage.py backfill_binary_tree --bundle <uuid>
    python manage.py backfill_binary_tree --dry-run

Algorithm:
    1. Sort all DistributorIDs by global_position (oldest → newest).
    2. First node becomes the company root.
    3. All remaining nodes are placed by one global FIFO/BFS queue.
    4. Sponsor genealogy is preserved for rewards/analytics only and does not
         influence binary placement.
"""

from django.core.management.base import BaseCommand, CommandError

from apps.business.binary_tree.services.binary_service import backfill_binary_tree


class Command(BaseCommand):
    help = 'Backfill strict company-root BFS binary placements from global order.'

    def add_arguments(self, parser):
        parser.add_argument(
            '--bundle',
            type=str,
            default=None,
            help='Only backfill for a specific OpportunityBundle UUID.',
        )
        parser.add_argument(
            '--dry-run',
            action='store_true',
            default=False,
            help='Simulate without writing to the database.',
        )

    def handle(self, *args, **options):
        bundle_id = options.get('bundle')
        dry_run = options.get('dry_run', False)

        self.stdout.write(
            self.style.NOTICE(
                f"Starting backfill_binary_tree "
                f"(bundle={bundle_id or 'ALL'}, dry_run={dry_run}) ..."
            )
        )

        try:
            result = backfill_binary_tree(bundle_id=bundle_id, dry_run=dry_run)
        except Exception as exc:
            raise CommandError(f"Backfill failed: {exc}") from exc

        self.stdout.write(self.style.SUCCESS(
            f"\nBackfill complete:\n"
            f"  Placed           : {result['placed']}\n"
            f"  Already placed   : {result['already_placed']}\n"
            f"  Skipped (no spnsr): {result['skipped_no_sponsor']}\n"
            f"  Errors           : {result['errors']}\n"
            f"  Dry run          : {result['dry_run']}"
        ))

        if result['errors'] > 0:
            self.stdout.write(self.style.WARNING(
                f"\nWARNING: {result['errors']} errors occurred. "
                "Check application logs for details."
            ))
