from django.core.management.base import BaseCommand

from apps.projects.fx import convert_fund
from apps.projects.models import ProjectFund


class Command(BaseCommand):
    help = "Backfill exchange_rate + amount_idr on existing funds (IDR conversion)."

    def add_arguments(self, parser):
        parser.add_argument(
            "--only-missing", action="store_true",
            help="Only funds with no amount_idr yet.",
        )

    def handle(self, *args, **options):
        qs = ProjectFund.objects.all()
        if options["only_missing"]:
            qs = qs.filter(amount_idr__isnull=True)

        changed = skipped = 0
        for fund in qs.iterator():
            if convert_fund(fund):
                changed += 1
                self.stdout.write(f"  {fund.source} {fund.currency} {fund.amount} → IDR {fund.amount_idr}")
            else:
                skipped += 1
        self.stdout.write(self.style.SUCCESS(f"Done. {changed} updated, {skipped} unchanged."))
