from django.db import transaction
from apps.banking.models import Bank, BankBranch
from apps.treasury.models import record_treasury_audit

NRB_DIRECTORY_VERSION = "NRB-BFI-2083-ASOJ"
NRB_DIRECTORY_SOURCE_DATE = "2026-10-15"

# Official Nepal Rastra Bank Licensed BFI Institutions (Class A, B, C)
NRB_LICENSED_BFIS = [
    # Class A — Commercial Banks
    {"short_code": "NBL", "name": "Nepal Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "NEBLNPKA"},
    {"short_code": "RBB", "name": "Rastriya Banijya Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "RBBANPKA"},
    {"short_code": "ADBL", "name": "Agricultural Development Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "ADBLNPKA"},
    {"short_code": "NABIL", "name": "Nabil Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "NARBNPKA"},
    {"short_code": "NIMB", "name": "Nepal Investment Mega Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "NIBLNPKT"},
    {"short_code": "SCBNL", "name": "Standard Chartered Bank Nepal Limited", "category": "CLASS_A_COMMERCIAL", "swift": "SCBLNPKA"},
    {"short_code": "HBL", "name": "Himalayan Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "HIMANPKA"},
    {"short_code": "NSBI", "name": "Nepal SBI Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "NSBINPKA"},
    {"short_code": "EBL", "name": "Everest Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "EVBLNPKA"},
    {"short_code": "KUMARI", "name": "Kumari Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "KMBLNPKA"},
    {"short_code": "LSL", "name": "Laxmi Sunrise Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "LXBLNPKA"},
    {"short_code": "CZBIL", "name": "Citizens Bank International Limited", "category": "CLASS_A_COMMERCIAL", "swift": "CTZNNPKA"},
    {"short_code": "PCBL", "name": "Prime Commercial Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "PCBLNPKA"},
    {"short_code": "PRVU", "name": "Prabhu Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "PRVUNPKA"},
    {"short_code": "GBIME", "name": "Global IME Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "GLBBNPKA"},
    {"short_code": "NMB", "name": "NMB Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "NMBBNPKA"},
    {"short_code": "MBL", "name": "Machhapuchchhre Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "MBLNNPKA"},
    {"short_code": "SBL", "name": "Siddhartha Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "SIDDNPKA"},
    {"short_code": "SANIMA", "name": "Sanima Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "SNMANPKA"},
    {"short_code": "NICA", "name": "NIC Asia Bank Limited", "category": "CLASS_A_COMMERCIAL", "swift": "NICENPKA"},
    # Class B — Development Banks (Major National/Regional)
    {"short_code": "MNBBL", "name": "Muktinath Bikas Bank Limited", "category": "CLASS_B_DEVELOPMENT", "swift": ""},
    {"short_code": "GBBL", "name": "Garima Bikas Bank Limited", "category": "CLASS_B_DEVELOPMENT", "swift": ""},
    {"short_code": "JBBL", "name": "Jyoti Bikas Bank Limited", "category": "CLASS_B_DEVELOPMENT", "swift": ""},
    {"short_code": "KSBBL", "name": "Kamana Sewa Bikas Bank Limited", "category": "CLASS_B_DEVELOPMENT", "swift": ""},
    {"short_code": "MLBL", "name": "Mahalaxmi Bikas Bank Limited", "category": "CLASS_B_DEVELOPMENT", "swift": ""},
    {"short_code": "SADBL", "name": "Shangrila Development Bank Limited", "category": "CLASS_B_DEVELOPMENT", "swift": ""},
    {"short_code": "LBBL", "name": "Lumbini Bikas Bank Limited", "category": "CLASS_B_DEVELOPMENT", "swift": ""},
    {"short_code": "SHINE", "name": "Shine Resunga Development Bank Limited", "category": "CLASS_B_DEVELOPMENT", "swift": ""},
    # Class C — Finance Companies (Major)
    {"short_code": "GFCL", "name": "Goodwill Finance Limited", "category": "CLASS_C_FINANCE", "swift": ""},
    {"short_code": "ICFC", "name": "ICFC Finance Limited", "category": "CLASS_C_FINANCE", "swift": ""},
    {"short_code": "MFIL", "name": "Manjushree Finance Limited", "category": "CLASS_C_FINANCE", "swift": ""},
    {"short_code": "RLFL", "name": "Reliance Finance Limited", "category": "CLASS_C_FINANCE", "swift": ""},
]


class NrbDirectorySyncService:
    @staticmethod
    @transaction.atomic
    def sync_company_banks(*, company, user=None) -> dict:
        created = 0
        updated = 0
        for idx, bfi in enumerate(NRB_LICENSED_BFIS, start=1):
            bank, is_new = Bank.objects.get_or_create(
                company=company,
                short_code=bfi["short_code"],
                defaults={
                    "name": bfi["name"],
                    "swift_code": bfi["swift"],
                    "bank_category": bfi["category"],
                    "nrb_institution_code": f"NRB-{idx:03d}",
                    "nrb_source_date": NRB_DIRECTORY_SOURCE_DATE,
                    "nrb_directory_version": NRB_DIRECTORY_VERSION,
                },
            )
            if is_new:
                created += 1
                BankBranch.objects.get_or_create(
                    bank=bank,
                    branch_code="HO",
                    defaults={"name": "Kathmandu Corporate Branch", "address": "Kathmandu, Nepal"},
                )
            else:
                changed = False
                if bank.bank_category != bfi["category"] or bank.nrb_directory_version != NRB_DIRECTORY_VERSION:
                    bank.bank_category = bfi["category"]
                    bank.nrb_source_date = NRB_DIRECTORY_SOURCE_DATE
                    bank.nrb_directory_version = NRB_DIRECTORY_VERSION
                    if bfi["swift"] and not bank.swift_code:
                        bank.swift_code = bfi["swift"]
                    bank.save(
                        update_fields=[
                            "bank_category",
                            "nrb_source_date",
                            "nrb_directory_version",
                            "swift_code",
                        ]
                    )
                    updated += 1
                if not bank.branches.exists():
                    BankBranch.objects.create(
                        bank=bank, branch_code="HO", name="Kathmandu Corporate Branch", address="Kathmandu, Nepal"
                    )

        record_treasury_audit(
            company=company,
            module="BANK_MASTER",
            action="NRB_BFI_DIRECTORY_SYNCED",
            entity_type="Bank",
            entity_id=NRB_DIRECTORY_VERSION,
            actor=user,
            new_state={"created": created, "updated": updated, "source_date": NRB_DIRECTORY_SOURCE_DATE},
        )
        return {
            "version": NRB_DIRECTORY_VERSION,
            "source_date": NRB_DIRECTORY_SOURCE_DATE,
            "created": created,
            "updated": updated,
            "total_catalog": len(NRB_LICENSED_BFIS),
        }

