"""
Supplier Accounts Normalizer

Normalizes supplier account numbers (Bankgiro/Plusgiro).
"""

import re
from .base import BaseNormalizer


class SupplierAccountsNormalizer(BaseNormalizer):
    """
    Normalizes supplier accounts field.

    The field may contain multiple accounts separated by ' | '.
    Format examples:
        'PG:48676043 | PG:49128028 | PG:8915035'
        'BG:5393-9484'

    Each account is normalized separately to generate variants.

    Examples:
        'PG:48676043' -> ['PG:48676043', '48676043', '4867604-3']
        'BG:5393-9484' -> ['BG:5393-9484', '5393-9484', '53939484']
    """

    def normalize(self, value: str) -> list[str]:
        """Generate variants of supplier accounts."""
        value = self.clean_text(value)
        variants = []

        # Split by ' | ' to handle multiple accounts
        accounts = [acc.strip() for acc in value.split('|')]

        for account in accounts:
            account = account.strip()
            if not account:
                continue

            # Add original value
            variants.append(account)

            # Remove prefix (PG:, BG:, etc.)
            if ':' in account:
                prefix, number = account.split(':', 1)
                number = number.strip()
                variants.append(number)  # Just the number without prefix

                # Also add with different prefix formats
                prefix_upper = prefix.strip().upper()
                variants.append(f"{prefix_upper}:{number}")
                variants.append(f"{prefix_upper}: {number}")  # With space
            else:
                number = account

            # Extract digits only
            digits_only = re.sub(r'\D', '', number)

            if digits_only:
                variants.append(digits_only)

                # Plusgiro format: XXXXXXX-X (7 digits + check digit)
                if len(digits_only) == 8:
                    with_dash = f"{digits_only[:-1]}-{digits_only[-1]}"
                    variants.append(with_dash)
                    # Also try 4-4 format for bankgiro
                    variants.append(f"{digits_only[:4]}-{digits_only[4:]}")
                elif len(digits_only) == 7:
                    with_dash = f"{digits_only[:-1]}-{digits_only[-1]}"
                    variants.append(with_dash)
                elif len(digits_only) == 10:
                    # 6-4 format (like org number)
                    variants.append(f"{digits_only[:6]}-{digits_only[6:]}")

        return list(set(v for v in variants if v))
