"""
Supplier Organization Number Normalizer

Handles normalization and validation of Swedish organization numbers.
"""

import re

from .base import BaseNormalizer, NormalizationResult


class SupplierOrgNumberNormalizer(BaseNormalizer):
    """
    Normalizes Swedish supplier organization numbers.

    Extracts organization number in format: NNNNNN-NNNN (10 digits)
    Also handles VAT numbers: SE + 10 digits + 01

    Examples:
        'org.nr. 516406-1102, Filialregistret...' -> '516406-1102'
        'Momsreg.nr SE556123456701' -> '556123-4567'
    """

    @property
    def field_name(self) -> str:
        return "supplier_org_number"

    def normalize(self, text: str) -> NormalizationResult:
        text = text.strip()
        if not text:
            return NormalizationResult.failure("Empty text")

        # Pattern 1: Standard org number format: NNNNNN-NNNN
        org_pattern = r"\b(\d{6})-?(\d{4})\b"
        match = re.search(org_pattern, text)
        if match:
            org_num = f"{match.group(1)}-{match.group(2)}"
            return NormalizationResult.success(org_num)

        # Pattern 2: VAT number format: SE + 10 digits + 01
        vat_pattern = r"SE\s*(\d{10})01"
        match = re.search(vat_pattern, text, re.IGNORECASE)
        if match:
            digits = match.group(1)
            org_num = f"{digits[:6]}-{digits[6:]}"
            return NormalizationResult.success(org_num)

        # Pattern 3: Just 10 consecutive digits
        digits_pattern = r"\b(\d{10})\b"
        match = re.search(digits_pattern, text)
        if match:
            digits = match.group(1)
            # Validate: first digit should be 1-9 for Swedish org numbers
            if digits[0] in "123456789":
                org_num = f"{digits[:6]}-{digits[6:]}"
                return NormalizationResult.success(org_num)

        return NormalizationResult.failure(
            f"Cannot extract org number from: {text[:100]}"
        )
