"""Run from any directory with PHP 8.4 on PATH. Uses a fresh, loopback-only installation."""
import base64, http.cookiejar, json, os, pathlib, re, secrets, shutil, socket, sqlite3, subprocess, tempfile, time, urllib.error, urllib.parse, urllib.request, uuid, hashlib, xml.etree.ElementTree as ET
root=pathlib.Path(__file__).resolve().parents[1]; tmp=tempfile.TemporaryDirectory(); work=pathlib.Path(tmp.name)
with socket.socket() as s:s.bind(('127.0.0.1',0));port=s.getsockname()[1]
url=f'http://127.0.0.1:{port}'; db=work/'test.sqlite';store=work/'storage'
for p in ['logs','framework/views','framework/sessions','framework/cache/data','app/private/photos']:(store/p).mkdir(parents=True,exist_ok=True)
env={**os.environ,'APP_ENV':'testing','APP_URL':url,'APP_KEY':'base64:'+base64.b64encode(secrets.token_bytes(32)).decode(),'APP_DEBUG':'false','SESSION_SECURE_COOKIE':'false','SESSION_DRIVER':'file','CACHE_STORE':'file','LOG_CHANNEL':'single','DB_DATABASE':str(db),'DB_CONNECTION':'sqlite','LARAVEL_STORAGE_PATH':str(store)}
mailboxes=['majorvehicles@gmail.com','greatbusesforsale@gmail.com'];keynames=['MVE_MAJOR_MAIL_KEY','MVE_GREAT_MAIL_KEY','MVE_SHEET_KEY'];keys=[secrets.token_hex(32) for _ in keynames];env.update(zip(keynames,keys))
def cli(*args,inp=None):return subprocess.run(['php','artisan',*args],input=inp,text=True,cwd=root,env=env,check=True,stdout=subprocess.PIPE).stdout
def client():return urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
guest=client();proc=None;log=open(work/'http.log','w')
def start():
 global proc
 proc=subprocess.Popen(['php','-S',f'127.0.0.1:{port}','-t','public','tests/router.php'],cwd=root,env=env,stdout=log,stderr=log)
 for _ in range(100):
  try:
   with socket.create_connection(('127.0.0.1',port),timeout=.2):return
  except OSError:time.sleep(.05)
 raise Exception('Server startup failed')
def stop():
 if proc and proc.poll() is None:proc.terminate();proc.wait(timeout=10)
def req(path,method='GET',data=None,c=None,status=200,headers=None):
 h={'Accept':'application/json','Origin':url,**(headers or {})}
 if isinstance(data,dict):h['Content-Type']='application/json';data=json.dumps(data).encode()
 try:r=(c or guest).open(urllib.request.Request(url+path,data=data,method=method,headers=h),timeout=20)
 except urllib.error.HTTPError as e:r=e
 with r:
  b=r.read();assert r.status==status,(path,r.status,b[:260]);return json.loads(b) if 'application/json' in r.headers.get('Content-Type','') else b.decode(errors='replace')
def account(c,email,password):
 html=req('/auth/sign-in',c=c);token=re.search(r'name="_token" value="([^"]+)',html)[1];return req('/auth/sign-in','POST',urllib.parse.urlencode(dict(_token=token,login=email,password=password)).encode(),c,headers={'Content-Type':'application/x-www-form-urlencoded'})
def bridge(channel,action,data):return req('/api/google/bridge/'+action,'POST',data,headers={'X-MVE-Channel':(mailboxes+['sheet'])[channel],'Authorization':'Bearer '+keys[channel]})
def mark(s):print('PASS '+s,flush=True)
try:
 cli('dealer:install');pw=secrets.token_urlsafe(22)
 for addr,role in [(mailboxes[0],'owner'),(mailboxes[1],'manager'),('writer@example.invalid','writer'),('accountant@example.invalid','accountant')]:cli('dealer:user',addr,role,inp=pw+'\n')
 start();m=json.loads((root/'resources/data/pages.json').read_text())
 for p,f in ([] if os.getenv('QUICK_WORKFLOW') else m.items()):
  html=req(p,headers={'Host':'getanybus.com'});assert hashlib.sha256(html.encode()).digest()==hashlib.sha256((root/'resources/pages'/f).read_bytes()).digest(),p
 if not os.getenv('QUICK_WORKFLOW'):mark(f'{len(m)} starting page responses match the shipped English and Spanish templates')
 red=json.loads((root/'resources/data/redirects.json').read_text())
 class NoRedirect(urllib.request.HTTPRedirectHandler):
  def redirect_request(self,*args):return None
 op=urllib.request.build_opener(urllib.request.ProxyHandler({}),NoRedirect())
 for p,target in {**red,'/new-inventory-detail-page/?stock=5352':'/inventory/a5352/','/es/new-inventory-detail-page/?stock=A5352':'/es/inventory/a5352/'}.items():
  try:op.open(url+p);raise AssertionError(p)
  except urllib.error.HTTPError as e:assert e.code==301 and e.headers['Location']==url+target,(p,e.code,e.headers['Location'],target)
 mark(f'{len(red)+2} old URL responses and destinations')
 req('/api/staff/data',status=401);owner,writer,acct=client(),client(),client()
 account(owner,'charles.kaufman@gmail.com',pw);account(writer,'writer@example.invalid',pw);account(acct,'accountant@example.invalid',pw)
 assert req('/api/staff/session',c=owner)['user']==mailboxes[0];req('/api/staff/blogs',c=writer);req('/api/staff/data',c=writer,status=403);req('/api/staff/inventory',c=acct,status=403);req('/api/staff/accounting',c=acct)
 mark('Charlie owner alias, writer and accountant role restrictions, anonymous access denied')
 d={'requestId':str(uuid.uuid4()),'name':'Sample Buyer','email':'test@example.invalid','source':'listing','stock':'A5352','question':'Can I inspect this bus?','newsletter':True}
 receipt=req('/api/inquiries','POST',d,status=201);assert req('/api/inquiries','POST',d)==receipt
 n=receipt['ticketNumber'];tid=receipt['ticketId'];since='2000-01-01T00:00:00Z'
 for i in range(2):
  messages=bridge(i,'notice',{'since':since})['rows'];assert len(messages)==1 and messages[0]['ticket_number']==n and messages[0]['stock']=='A5352'
 reply={'ticket':f'MVE Ticket #{n}','message':'local-message-1','date':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'subject':f'Re: [MVE Ticket #{n}]','body':'Please send details.','sender':d['email'],'recipients':[mailboxes[0]]}
 assert bridge(0,'import',reply)['inserted'];assert not bridge(0,'import',reply)['inserted'];state=req('/api/staff/data',c=owner);assert len(state['tickets'])==1 and any(r['kind']=='buyer_email' and r['ticket_id']==tid for r in state['activity'])
 mark('Buyer inquiry, retry, both simulated mailbox feeds and one threaded buyer reply')
 jar=next(h.cookiejar for h in owner.handlers if hasattr(h,'cookiejar'));cookie='; '.join(f'{c.name}={c.value}' for c in jar)
 if shutil.which('node'):subprocess.run(['node',str(root/'tests/mail-flows.mjs'),'--run'],input=json.dumps(dict(origin=url,majorKey=keys[0],greatKey=keys[1],sheetKey=keys[2],ownerCookie=cookie)),text=True,check=True)
 inv=req('/api/staff/inventory',c=owner);row=next(r for r in inv['rows'] if r['stock']=='A5352');bus=row['bus'];path='/api/staff/inventory'
 test={**bus,'editExisting':True,'version':0,'action':'draft','price':23888};req(path,'POST',test,owner);assert '$18,900' in req('/inventory/a5352/') and '$23,888' not in req('/inventory/a5352/')
 jpg=next((root/'public/photos').glob('*.jpg')).read_bytes();photo=req('/api/staff/photos','POST',jpg,owner,headers={'Content-Type':'image/jpeg'})['path'];req(photo,status=404)
 test.update(version=1,action='publish_only',images=[photo,*bus['images']]);v=req(path,'POST',test,owner);assert v['queued']==0 and v['version']==2
 for p in ['/','/?lang=es','/inventory/a5352/','/es/inventory/a5352/']:assert '$23,888' in req(p),p
 req(photo);req(path,'POST',test,owner,status=409)
 mark('Private draft, edited price, ordered JPEG upload, public price in both languages, no email on Update Live, stale save rejected')
 test.update(version=2,action='sold',soldCover=photo);req(path,'POST',test,owner);assert 'A5352' in req('/sold-buses/') and 'Sold · Stock A5352' in req('/inventory/a5352/')
 saved=req('/api/staff/accounting',c=acct);sale=next(r for r in saved['rows'] if r['stock']=='A5352');req('/api/staff/accounting','POST',{'key':sale['key'],'version':0,'changes':{'city':'Test City'}},acct)
 stop();start();assert 'Sold · Stock A5352' in req('/inventory/a5352/') and req(photo);mark('Sold archive, accountant sale record and persistence after PHP restart')
 from editor_workflows import run as check_editors
 check_editors(req, owner, writer, acct, db, root, bridge, mark)
 # Backup and restore into a separate database and private photo directory.
 stop()
 snapshot=work/'snapshot'
 subprocess.run(['php','tools/private-data.php','backup',str(db),str(store/'app/private/photos'),str(snapshot)],cwd=root,env=env,check=True)
 restored=work/'restored'
 shutil.copytree(snapshot/'photos',restored/'app/private/photos')
 for sub in ['framework/sessions','framework/cache/data','framework/views','logs']:(restored/sub).mkdir(parents=True,exist_ok=True)
 env['DB_DATABASE']=str(snapshot/'database.sqlite');env['LARAVEL_STORAGE_PATH']=str(restored);start()
 account(owner,mailboxes[0],pw);assert any(t['id']==tid for t in req('/api/staff/data',c=owner)['tickets']);assert req(photo);assert 'Sold · Stock A5352' in req('/inventory/a5352/');mark('Restored independent database and photo copies, signed in, retrieved inquiry and vehicle')
 from desk_regressions import check_desk
 check_desk(req, cli, account, client, owner, pw, bridge, mailboxes, root, url)
finally:
 stop();log.close()
 if __import__('sys').exc_info()[0]:
  for f in (work/'http.log',*store.glob('logs/*.log')):
   if f.exists():print(f.name,('\n'.join(x for x in f.read_text(errors='replace').splitlines() if 'ERROR' in x or 'Fatal' in x))[-700:])
 tmp.cleanup()
