import re
from extractors.base import ExtractResult
from utils.text import AADHAAR_RX, DOB_RX, PIN_RX, mask_aadhaar

def extract_aadhaar(text: str) -> ExtractResult:
    lines = [l.strip() for l in text.splitlines() if l.strip()]
    uid = None
    name = None
    dob = None
    gender = None
    address = None

    trans = str.maketrans('০১২৩৪৫৬৭৮৯', '0123456789')
    text = text.translate(trans)
    lines = [l.translate(trans) for l in lines]

    for l in lines:
        if uid is None:
            m = AADHAAR_RX.search(l)
            if m: uid = m.group(1)
        if dob is None:
            m = DOB_RX.search(l)
            if m: dob = m.group(1)
        if gender is None:
            if re.search(r"\bmale|पुरुष|পুরुष\b", l, re.I): gender = "Male"
            elif re.search(r"\bfemale|महिला|মহিলা\b", l, re.I): gender = "Female"

    if uid:
        try:
            idx = next(i for i,l in enumerate(lines) if uid.replace(' ','') in l.replace(' ',''))
            for j in range(max(0, idx-3), idx):
                if len(lines[j].split()) >= 2 and not re.search(r"\d{4,}", lines[j]):
                    name = lines[j]
                    break
        except StopIteration:
            pass

    addr = []
    started = False
    for l in lines:
        if re.search(r"address|ঠিকানা|address\b", l, re.I):
            started = True
            continue
        if started:
            addr.append(l)
    if not addr and uid:
        try:
            idx = next(i for i,l in enumerate(lines) if uid.replace(' ','') in l.replace(' ',''))
            addr = lines[idx+1: idx+6]
        except StopIteration:
            pass
    address = ", ".join(addr) if addr else None

    pin = None
    if address:
        m = PIN_RX.search(address)
        if m: pin = m.group(1)

    fields = {
        "aadhaar_masked": mask_aadhaar(uid) if uid else None,
        "aadhaar_raw": uid,
        "name": name,
        "dob": dob,
        "gender": gender,
        "address": address,
        "pincode": pin,
    }
    filled = sum(1 for v in fields.values() if v)
    conf = min(0.98, 0.4 + 0.12*filled)
    return ExtractResult("aadhaar", fields, conf)
