import re


POULTRY_TEXT = {
    "local_name": "جاوید تسل تجارتی شرکت",
    "invoice_tagline": "د نړۍ د معتبرو کمپنیو څخه حیواني درمل، واکسین او زراعتي درمل، سامان آلات په لوړه معیار او مناسب قیمت تر لاسه کولای شئ.",
    "contact_person": "جاوید (تسل) / ډاکټر هدایت الله",
    "facebook": "جاوید تسل تجارتی شرکت",
    "address": "جلال آباد ښار، د درمسال چوک، نور عمر پلازه زیر زمین 5-6-7 نمبر دفتر",
}


def damaged_text(value):
    return bool(re.search(r"\?{3,}|\ufffd", value or ""))


def recover_profile_text(attrs, instance=None):
    """Prefer saved readable text over a damaged submission from a stale form."""
    template = attrs.get("invoice_template", getattr(instance, "invoice_template", None))
    for field, value in list(attrs.items()):
        if not isinstance(value, str) or not damaged_text(value):
            continue
        saved = getattr(instance, field, "") if instance else ""
        if isinstance(saved, str) and saved and not damaged_text(saved):
            attrs[field] = saved
        elif template == "jawid_poultry" and field in POULTRY_TEXT:
            # Only replace completely lost text; partially readable custom text
            # needs the author's correction rather than a guessed replacement.
            if not any(char.isalpha() for char in value):
                attrs[field] = POULTRY_TEXT[field]
    return attrs
