from __future__ import annotations
import re, unicodedata


def norm(s):
    s=(s or '').casefold().replace('ı','i').replace('İ','i')
    s=''.join(c for c in unicodedata.normalize('NFKD',s) if not unicodedata.combining(c))
    return re.sub(r'[^a-z0-9]+',' ',s).strip()


def tokens(s):
    return [x for x in norm(s).split() if len(x)>=2]


def confidence(product,title,html):
    title_n=norm(title)
    important=[]
    for field in ('brand','model','variant'):
        important += tokens(product.get(field) if hasattr(product,'get') else product[field])
    important=list(dict.fromkeys(important))
    score=0.55 if not important else sum(1 for t in important if t in title_n)/len(important)*0.75
    ean=((product.get('ean') if hasattr(product,'get') else product['ean']) or '').strip()
    if ean and ean in html: score += 0.25
    elif ean and ean in title_n: score += 0.25
    return min(1.0,score)


def validate_product_match(product,title):
    title_n=norm(title)
    get=lambda k: product.get(k) if hasattr(product,'get') else product[k]
    bt=tokens(get('brand'))
    if bt and not any(t in title_n for t in bt):
        raise ValueError('Ürün başlığında marka eşleşmedi')
    for t in tokens(get('model')):
        if any(ch.isdigit() for ch in t) and t not in title_n:
            raise ValueError(f'Model belirteci eşleşmedi: {t}')
    for t in tokens(get('variant')):
        if any(ch.isdigit() for ch in t) and t not in title_n:
            raise ValueError(f'Varyant belirteci eşleşmedi: {t}')
