import os,sys,time,subprocess,threading,shutil,re,json,datetime,signal,urllib.request
from pathlib import Path
ROOT=Path(__file__).parent
side=sys.argv[1]; wt=Path(sys.argv[2]); out=ROOT/(side+'-'+datetime.datetime.now().strftime('%H%M%S')); out.mkdir()
t0=time.monotonic(); events=[]; lines=[]; cv=threading.Condition()
def emit(s):
 with cv:
  events.append([round(time.monotonic()-t0,3),s]); print(f'{events[-1][0]:07.2f}s {s}',flush=True); cv.notify_all()
def count(s): return sum(s in x for x in lines)
def wait_count(s,n,timeout=100):
 with cv:
  return cv.wait_for(lambda:count(s)>=n,timeout)
shutil.copytree(wt/'apps/server/src',wt/'apps/server-src-replacement')
sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=wt,text=True).strip()
emit(f'{side.upper()} commit {sha[:10]} | Linux x86_64 | Node '+subprocess.check_output(['node','--version'],text=True).strip())
emit('Fresh worktree database; T3CODE_DEV_SEED=0 vp run dev')
env=os.environ.copy(); env['T3CODE_DEV_SEED']='0'
p=subprocess.Popen(['vp','run','dev'],cwd=wt,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,bufsize=1)
raw=open(out/'raw-private.log','w')
def read():
 for line in p.stdout:
  raw.write(line);raw.flush()
  clean=re.sub(r'\x1b\[[0-9;]*[a-zA-Z]','',line).strip()
  with cv: lines.append(clean);cv.notify_all()
  if ('[dev] Restarting' in clean or 'Listening on http' in clean or 'REPRO-47160' in clean):
   # Retain only public watcher, readiness, and synthetic marker messages.
   if '[dev] Restarting' in clean: emit(clean[clean.index('[dev] Restarting'):])
   elif 'Listening on http' in clean: emit(clean[clean.index('Listening on http'):])
   elif 'REPRO-47160' in clean: emit(clean[clean.index('REPRO-47160'):])
threading.Thread(target=read,daemon=True).start()
try:
 if not wait_count('Listening on http',1,180): raise RuntimeError('startup did not become ready')
 time.sleep(2)
 emit('ACTION: mv apps/server/src apps/server/src-old; mv apps/server-src-replacement apps/server/src')
 os.rename(wt/'apps/server/src',wt/'apps/server/src-old');os.rename(wt/'apps/server-src-replacement',wt/'apps/server/src')
 wait_count('Listening on http',2,30);time.sleep(2)
 start=count('[dev] Restarting')
 emit('ACTION: append console.log("REPRO-47160 replacement edit loaded") to replacement src/bin.ts')
 with open(wt/'apps/server/src/bin.ts','a') as f:f.write('\nconsole.log("REPRO-47160 replacement edit loaded");\n')
 time.sleep(30)
 marker=count('REPRO-47160 replacement edit loaded')
 emit(f'OBSERVED after 30s: restarts={count("[dev] Restarting")-start}; replacement marker occurrences={marker}')
 start=count('[dev] Restarting');ready=count('Listening on http')
 emit('ACTION: append comment to replacement src/entrypoint.ts')
 with open(wt/'apps/server/src/entrypoint.ts','a') as f:f.write('\n// REPRO-47160 follow-up edit\n')
 time.sleep(20)
 follow=count('[dev] Restarting')-start
 emit(f'OBSERVED after 20s: restarts={follow}; new ready messages={count("Listening on http")-ready}')
 start=count('[dev] Restarting')
 emit('CONTROL: append comment to moved-aside src-old/entrypoint.ts')
 with open(wt/'apps/server/src-old/entrypoint.ts','a') as f:f.write('\n// REPRO-47160 old tree control\n')
 time.sleep(20)
 emit(f'OBSERVED after 20s: old-tree edit restarts={count("[dev] Restarting")-start}')
 port=re.search(r'Listening on http://127.0.0.1:(\d+)', '\n'.join(lines)).group(1)
 class NoRedirect(urllib.request.HTTPRedirectHandler):
  def redirect_request(self,*args):return None
 try: status=urllib.request.build_opener(NoRedirect).open('http://127.0.0.1:'+port+'/').status
 except urllib.error.HTTPError as e:status=e.code
 emit(f'HTTP GET / -> {status}; server remains alive')
 emit(f'RESULT: replacement marker loaded={marker>0}; later replacement edit restarted={follow>0}')
finally:
 p.send_signal(signal.SIGTERM)
 try:p.wait(timeout=15)
 except subprocess.TimeoutExpired:p.kill();p.wait()
 emit('Dev task stopped')
 (out/'events.json').write_text(json.dumps(events,indent=2))
 (out/'transcript.txt').write_text('\n'.join(f'{t:07.2f}s {s}' for t,s in events)+'\n')
 with open(out/'recording.cast','w') as f:
  f.write(json.dumps({'version':2,'width':120,'height':32,'title':side+' real dev watcher reproduction'})+'\n')
  for t,s in events:f.write(json.dumps([t,'o',f'{t:07.2f}s {s}\r\n'])+'\n')
 print('ARTIFACTS',out,flush=True)
