"""Non-submitting identity read-back for live ATS review sessions."""
import re
from form_completion import _label, _profile_values

LABELS={'english first name':'first_name','first name':'first_name','given name':'first_name',
        'english last name':'last_name','last name':'last_name','family name':'last_name',
        'email':'email','email address':'email','e-mail':'email','phone':'phone','phone number':'phone'}
DISPLAY={'first_name':'English First Name','last_name':'English Last Name','email':'Email','phone':'Phone Number'}

def inspect(page,profile,repair=False):
    """Read live controls, optionally restore uniquely mapped identity controls once.

    Never fill during a privacy dialog. Never claim verification for ambiguous or
    missing fields. The caller owns consent handling and the review session.
    """
    approved=_profile_values(profile)
    found={k:[] for k in DISPLAY}
    for frame in page.frames:
        controls=frame.locator('input:not([type="hidden"]):not([type="file"])')
        for i in range(min(controls.count(),220)):
            el=controls.nth(i)
            try:
                if not el.is_visible() or not el.is_enabled():continue
                label=re.sub(r'\s+',' ',_label(el)).strip().lower().rstrip(':')
                key=LABELS.get(label)
                if not key:
                    placeholder=(el.get_attribute('placeholder') or '').strip().lower()
                    ident=(el.get_attribute('id') or '').lower()
                    if placeholder=='phone number' or re.search(r'contact_information_phone$',ident):key='phone'
                if key:found[key].append(el)
            except Exception:continue
    outcome=[]
    for key,title in DISPLAY.items():
        expected=str(approved.get(key,'')).strip()
        matches=found[key]
        if not matches:result='needs review — live field not found'
        elif len(matches)!=1:result='needs review — multiple matching fields'
        elif not expected:result='needs input — approved profile value missing'
        else:
            el=matches[0]
            try:
                actual=el.input_value().strip()
                if actual!=expected and repair:
                    el.fill(expected,timeout=4000)
                    el.blur(timeout=2000)
                    page.wait_for_timeout(650)
                # Read again from live DOM, not a stale Playwright node.
                if el.is_visible() and el.input_value().strip()==expected:result='verified'
                else:result='needs review — live value differs from approved profile'
            except Exception:result='needs review — field changed during verification'
        outcome.append({'field':title,'result':result})
    return outcome

def merge(results,audit):
    titles=set(DISPLAY.values())
    return [r for r in results if r.get('field') not in titles]+audit
