"""Flag drift between BudgetCommitment totals and the GL encumbrance balance.

Usage:
    python manage.py reconcile_budget_commitments

Exits non-zero if any drift is found (cron/CI friendly).
"""
from django.core.management.base import BaseCommand

from apps.companies.models import Organization
from apps.procurements.reconciliation import reconcile_budget_commitments


class Command(BaseCommand):
    help = "Report budget items where BudgetCommitment drifts from the GL encumbrance balance."

    def handle(self, *args, **opts):
        all_findings = []
        for org in Organization.objects.all():
            for f in reconcile_budget_commitments(org):
                all_findings.append({**f, "organization": org.name})

        if not all_findings:
            self.stdout.write(self.style.SUCCESS("No drift found."))
            return

        for f in all_findings:
            self.stdout.write(self.style.WARNING(
                f"[{f['organization']}] {f['budget_item_name']} ({f['budget_item_id']}): "
                f"commitments={f['active_commitments']} gl_encumbrance={f['gl_encumbrance_balance']} "
                f"drift={f['drift']}"
            ))
        self.stderr.write(self.style.ERROR(f"{len(all_findings)} budget item(s) drifted."))
        raise SystemExit(1)
