"""Public ATS enrichment for user-supplied LinkedIn job seeds. No login or CRM writes."""
import argparse,csv,json,subprocess,datetime,re
from pathlib import Path
from collections import Counter
from urllib.parse import quote

def fetch(board):
 if not re.fullmatch(r'[A-Za-z0-9._-]{1,100}',board): raise ValueError('Invalid Ashby board')
 r=subprocess.run(['curl','--fail','--silent','--show-error','--max-time','25','-A','Mozilla/5.0','-H','Accept: application/json','https://api.ashbyhq.com/posting-api/job-board/'+quote(board)],capture_output=True,text=True)
 if r.returncode: raise RuntimeError(r.stderr.strip())
 data=json.loads(r.stdout)
 if not isinstance(data.get('jobs'),list): raise ValueError('Missing jobs list')
 jobs={j['id']:j for j in data['jobs'] if j.get('isListed',True)}
 clean=[{k:j.get(k) for k in ['id','title','department','team','employmentType','location','secondaryLocations','workplaceType','publishedAt','jobUrl']} for j in jobs.values()]
 return {'status':'complete','provider':'ashby_public_posting_api','jobs':clean,'total':len(clean),'engineering_department':sum(j['department']=='Engineering' for j in clean),'counts':{k:dict(Counter(j.get(k) or 'Unknown' for j in clean)) for k in ['department','team','employmentType','location','workplaceType']}}

def main():
 p=argparse.ArgumentParser();p.add_argument('--seeds',type=Path);p.add_argument('--smoke-board');p.add_argument('--out',type=Path,required=True);a=p.parse_args()
 if not a.seeds and not a.smoke_board:p.error('Provide --seeds or --smoke-board')
 rows=list(csv.DictReader(a.seeds.open())) if a.seeds else [{'company':a.smoke_board,'ats_board':a.smoke_board,'ats_provider':'ashby','origin':'connector_smoke_test_not_linkedin_discovery'}]
 result={'observed_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'mode':'seed_enrichment' if a.seeds else 'connector_smoke_test','crm_writes':0,'messages_sent':0,'accounts':[]}
 for seed in rows[:15]:
  try:
   if seed.get('ats_provider')!='ashby':raise ValueError('Unsupported provider: requires manual adapter review')
   record=fetch(seed['ats_board'])
  except Exception as e:record={'status':'failed','total':None,'error':str(e)}
  result['accounts'].append({'seed':seed,**record})
 a.out.parent.mkdir(parents=True,exist_ok=True);a.out.write_text(json.dumps(result,ensure_ascii=False,indent=2))
 print(json.dumps({'mode':result['mode'],'results':[{'company':r['seed'].get('company'),'status':r['status'],'total':r.get('total')} for r in result['accounts']]},ensure_ascii=False))
if __name__=='__main__':main()
