import os,sys,json,time,subprocess,pathlib,urllib.request,sqlite3,uuid,datetime,signal
ROOT=pathlib.Path(__file__).resolve().parent
RUN=ROOT/('run-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')); RUN.mkdir()
# Read the dedicated test account without printing credentials.
ENV={k:v for k,v in os.environ.items() if k.startswith('LINEAR_')}
def linear(query,variables={}):
 req=urllib.request.Request('https://api.linear.app/graphql',data=json.dumps({'query':query,'variables':variables}).encode(),headers={'Content-Type':'application/json','Authorization':ENV['LINEAR_API_KEY']})
 data=json.load(urllib.request.urlopen(req))
 if data.get('errors'): raise RuntimeError(json.dumps(data['errors']))
 return data['data']
class Side:
 def __init__(self,label,checkout,port):
  self.label=label;self.checkout=pathlib.Path(checkout);self.home=RUN/label;self.home.mkdir();(self.home/'userdata').mkdir();(self.home/'workflows').mkdir();self.port=port;self.proc=None;self.issues=[];self.project=str(uuid.uuid4());self.events=[]
  (self.home/'userdata/settings.json').write_text(json.dumps({'workflowsEnabled':True,'workflowSkippedRunsKept':0}))
  self.sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=self.checkout,text=True).strip()
 def log(self,text,**data):
  event={'time':datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='milliseconds'),'message':text,**data};self.events.append(event)
  with (RUN/(self.label+'-transcript.jsonl')).open('a') as f:f.write(json.dumps(event)+'\n')
  print(self.label.upper(),json.dumps(event),flush=True)
 def start(self):
  self.serverlog=(self.home/('server-'+str(time.time_ns())+'.log')).open('w')
  self.proc=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--host','127.0.0.1','--port',str(self.port),'--base-dir',str(self.home)],cwd=self.checkout,env={**os.environ,'T3CODE_DEV_SEED':'0','T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD':'0','T3CODE_WORKFLOWS':str(self.home/'workflows')},stdout=self.serverlog,stderr=subprocess.STDOUT)
  for _ in range(180):
   if self.proc.poll() is not None:raise RuntimeError('Server exited: '+self.serverlog.name)
   try:
    urllib.request.urlopen(f'http://127.0.0.1:{self.port}/.well-known/t3/environment',timeout=1);break
   except Exception:time.sleep(.5)
  else:raise RuntimeError('Server startup timed out')
  self.log('Real T3 server listening',commit=self.sha)
 def stop(self):
  if self.proc and self.proc.poll() is None:
   self.proc.send_signal(signal.SIGTERM)
   try:self.proc.wait(timeout=20)
   except subprocess.TimeoutExpired:self.proc.kill();self.proc.wait()
   self.serverlog.close();self.log('Server fully stopped')
 def rpc(self,calls):
  proc=subprocess.run(['node','--input-type=module'],input=(ROOT/'rpc.mjs').read_text(),cwd=self.checkout/'apps/server',env={**os.environ,'PROOF_CHECKOUT':str(self.checkout),'PROOF_HOME':str(self.home),'PROOF_CALLS':json.dumps(calls)},text=True,capture_output=True,timeout=60)
  if proc.returncode:raise RuntimeError(proc.stderr[-3000:])
  return [json.loads(x) for x in proc.stdout.splitlines() if x.startswith('{')]
 def sql(self,q):
  with sqlite3.connect(f'file:{self.home}/userdata/statev2.sqlite?mode=ro',uri=True) as db:
   db.row_factory=sqlite3.Row;return [dict(x) for x in db.execute(q)]
 def comments(self):
  return linear('query($id:String!){issue(id:$id){identifier createdAt comments{nodes{body createdAt}}}}',{'id':self.issues[0]['id']})['issue']
 def setup(self):
  self.start()
  folder=self.home/'project';folder.mkdir();subprocess.run(['git','init','--quiet',str(folder)],check=True)
  self.rpc([['projects.mutate',{'type':'project.create','commandId':str(uuid.uuid4()),'projectId':self.project,'title':'Workflow prune proof','workspaceRoot':str(folder)}],['issueTrackers.connect',{'tracker':'linear','token':ENV['LINEAR_API_KEY']}],['issueTrackers.bindProject',{'projectId':self.project,'binding':{'tracker':'linear','scope':ENV['LINEAR_TEST_TEAM_KEY']}}]])
  self.tag='pr46474-'+self.label+'-'+uuid.uuid4().hex[:10]
  workflow='''const { workflow, step, issues, skip, Issue } = T3;
workflow("issue-ping", {version:1, payload:Issue, triggers:[issues.opened({project:PROJECT,query:TAG})]}, Effect.fn(function* (issue) {
 yield* step("comment", { returns: Schema.Void }, issues.comment(issue, "Workflow issue-ping saw this issue."));
 yield* skip("only a ping");
}));
'''.replace('PROJECT',json.dumps(self.project)).replace('TAG',json.dumps(self.tag))
  (self.home/'workflows/issue-ping.ts').write_text(workflow)
  for _ in range(180):
   cursors=self.sql('select * from workflow_triggers')
   if cursors:break
   time.sleep(1)
  else:raise RuntimeError('No initial trigger cursor')
  self.log('Workflow registered; first poll initialized cursor',cursors=cursors)
  issue=linear('mutation($input:IssueCreateInput!){issueCreate(input:$input){success issue{id identifier createdAt title}}}',{'input':{'teamId':ENV['LINEAR_TEST_TEAM_ID'],'title':self.tag+' opened issue'}})['issueCreate']['issue'];self.issues.append(issue)
  self.log('Filed real Linear issue after first poll',issue=issue)
 def wait_first(self):
  for _ in range(150):
   runs=self.sql('select run_id,status,started_at,ended_at,engine_pruned_at from workflow_runs')
   if runs and runs[0]['status']=='skipped':break
   if runs and runs[0]['status']=='paused':raise RuntimeError('Workflow paused: '+str(self.sql('select detail from workflow_runs')))
   time.sleep(1)
  else:raise RuntimeError('Workflow did not finish')
  self.log('Original workflow finished skipped',runs=runs,linear=self.comments(),cursors=self.sql('select * from workflow_triggers'))
  self.stop();self.start()
 def control(self):
  self.log('Control restart before pruning: existing run prevents duplicate',runs=self.sql('select run_id,status,ended_at from workflow_runs'),linear=self.comments())
 def cleanup(self):
  self.stop()
  for issue in self.issues:
   linear('mutation($id:String!){issueDelete(id:$id){success}}',{'id':issue['id']})
  self.log('Deleted synthetic Linear issues')
sides=[Side('before',os.environ['PROOF_BASE'],19274),Side('after',os.environ['PROOF_HEAD'],19275)]
try:
 for s in sides:s.setup()
 for s in sides:s.wait_first()
 time.sleep(70)
 for s in sides:s.control()
 print('WAITING_FOR_REAL_ONE_HOUR_PRUNE',str(RUN),flush=True)
 pending=list(sides);deadline=time.monotonic()+3700
 while pending:
  for s in pending[:]:
   if not s.sql('select run_id from workflow_runs'):
    s.log('Natural retention sweep pruned skipped run; workflow_runs is empty',cursors=s.sql('select * from workflow_triggers'),linear=s.comments())
    if s.label=='after':s.log('Durable opened-item receipt remains',receipts=s.sql('select * from workflow_opened_run_receipts'))
    s.stop();pending.remove(s)
  if time.monotonic()>deadline:raise RuntimeError('Natural pruning timed out')
  if pending:time.sleep(.25)
 for s in sides:s.start()
 time.sleep(75)
 for s in sides:
  s.log('First poll after prune and restart',runs=s.sql('select run_id,status,started_at,ended_at from workflow_runs'),linear=s.comments(),cursors=s.sql('select * from workflow_triggers'))
 (RUN/'complete').write_text('complete')
 print('PRIMARY_PROOF_COMPLETE',flush=True)
 # Remain available for inspecting the real server before cleanup.
 while not (RUN/'finish').exists():time.sleep(1)
finally:
 for s in sides:
  try:s.cleanup()
  except Exception as e:print('CLEANUP_ERROR',s.label,str(e),flush=True)
