#!/usr/bin/env python3
"""AccessLens local, candidate-controlled browser assistant.

No login/CAPTCHA bypass, no form submission, no unattended bulk application.
"""
import argparse, json, re, sys
from pathlib import Path
from urllib.parse import urlparse

SUPPORTED = ('boards.greenhouse.io','job-boards.greenhouse.io','jobs.lever.co')
HANDOFF = ('naukri.com','linkedin.com','foundit.in','instahyre.com','cutshort.io','indeed.com','indeed.co.in','hirist.tech','wellfound.com','iimjobs.com','shine.com','timesjobs.com','myworkdayjobs.com')

def platform(url):
    parsed=urlparse(url)
    host=(parsed.hostname or '').lower()
    if parsed.scheme!='https' or not host: return 'invalid'
    if any(host==d or host.endswith('.'+d) for d in SUPPORTED): return 'supported'
    if any(host==d or host.endswith('.'+d) for d in HANDOFF): return 'manual_handoff'
    return 'unknown'

def load_json(path):
    data=json.loads(Path(path).read_text(encoding='utf-8'))
    if not isinstance(data,dict): raise ValueError('Expected JSON object')
    return data

def safe_profile(p):
    allowed=('full_name','email','phone','location','address_line1','address_line2','city','state','postal_code','country','phone_country_code','linkedin','portfolio','notice_period','current_company','years_experience','education','work_authorization')
    return {k:str(p.get(k,'')).strip()[:500] for k in allowed if p.get(k)}

def run(url, profile, resume=None, fill=False):
    mode=platform(url)
    if mode!='supported':
        print(json.dumps({'mode':mode,'message':'Use candidate-controlled manual handoff. This URL is not approved for browser autofill.'},indent=2))
        return 2
    try:
        from playwright.sync_api import sync_playwright
    except ImportError:
        print('Install: python3 -m pip install playwright && python3 -m playwright install chromium',file=sys.stderr)
        return 3
    with sync_playwright() as pw:
        browser=pw.chromium.launch(headless=False)
        page=browser.new_page()
        try:
            page.goto(url,wait_until='domcontentloaded',timeout=30000)
            print('Opened:',page.url)
            if fill:
                mapping={
                    'full_name':['input[name="name"]','input[autocomplete="name"]'],
                    'email':['input[type="email"]','input[autocomplete="email"]'],
                    'phone':['input[type="tel"]','input[autocomplete="tel"]'],
                    'linkedin':['input[name*="linkedin" i]'],
                    'location':['input[name*="location" i]'],
                }
                for key, selectors in mapping.items():
                    val=profile.get(key,'')
                    if not val: continue
                    for selector in selectors:
                        loc=page.locator(selector)
                        if loc.count()==1 and loc.is_visible() and not loc.input_value().strip():
                            loc.fill(val);print('Filled:',key);break
                if resume:
                    # Resume attachment is opt-in; do not guess which of multiple upload inputs is correct.
                    loc=page.locator('input[type="file"]')
                    if loc.count()==1:
                        loc.set_input_files(str(Path(resume).resolve()))
                        print('Attached resume to sole file upload field; verify before submitting.')
                    else:
                        print('Resume upload requires manual selection (ambiguous or missing upload field).')
            print('REVIEW REQUIRED: Browser will not submit the form. Complete any missing fields yourself.')
            input('Press Enter in Terminal to close the browser (do not enter passwords here)...')
        finally:
            browser.close()
    return 0

if __name__=='__main__':
    parser=argparse.ArgumentParser(description='Candidate-controlled AccessLens application assistant')
    parser.add_argument('--url',required=True,help='HTTPS Greenhouse or Lever employer application URL')
    parser.add_argument('--profile',required=True,help='Local JSON profile exported from AccessLens')
    parser.add_argument('--resume',help='Path to approved resume DOCX/PDF (optional)')
    parser.add_argument('--fill',action='store_true',help='Fill unambiguous empty fields; default inspect-only')
    args=parser.parse_args()
    try:
        if args.resume and not Path(args.resume).is_file(): raise ValueError('Resume file not found')
        sys.exit(run(args.url,safe_profile(load_json(args.profile)),args.resume,args.fill))
    except (ValueError,OSError,json.JSONDecodeError) as e:
        print('Error:',e,file=sys.stderr);sys.exit(1)
