import { execFileSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { expect } from 'e2e';
import { MOBILE_T3_HOME } from '../e2e.config.ts';
import { environmentId, runPromise } from './t3.ts';
import { test, IOS } from './t3-mobile.ts';

test('Mobile Activity cross-reference opens its pull request', IOS, async ({t3,app,screen,device})=>{
 const project=await t3.project('Mobile reference proof');
 execFileSync('git',['remote','add','origin','https://github.com/pingdotgg/t3code.git'],{cwd:project});
 const id=execFileSync('sqlite3',[`${MOBILE_T3_HOME}/userdata/statev2.sqlite`,"select project_id from projection_projects where title='Mobile reference proof' limit 1;"],{encoding:'utf8'}).trim();
 await t3.open();
 const {origin}=JSON.parse(readFileSync(`${MOBILE_T3_HOME}/userdata/server-runtime.json`,'utf8'));
 const env=await runPromise(environmentId(origin));
 const results:boolean[]=[];
 for(const target of [
   {number:40346,kind:'pr',title:'feat(web): repository rows in thread details open their diff'},
   {number:40760,kind:'issue',title:'Issue Activity cross-references ("referenced this from owner/repo#N") are plain text and cannot be opened'},
 ]) {
   await device.openLink(`t3code-dev://issues/${env}/${id}/github/pingdotgg%2Ft3code/40318`,{app:'com.t3tools.t3code.dev'});
   await device.alert('accept').catch(()=>{});
   await screen.getByText('#40318',{exact:true}).waitFor({timeout:60000});
   await screen.scrollUntilVisible(screen.getByText('referenced this from',{exact:false}).first(),{direction:'down',momentum:'slow',timeout:90000});
   await screen.swipe({direction:'down'});
   const ref=screen.getByText(`pingdotgg/t3code#${target.number}`,{exact:false}).last();
   await app.screenshot(`mobile-${target.kind}-activity-reference-visible`);
   const linked=await screen.getByRole('link',`pingdotgg/t3code#${target.number}`,{exact:true}).isVisible();
   const box=await ref.boundingBox();
   if(!box) throw new Error('Activity reference has no visible bounds');
   await ref.tap({position:{x:box.width/2,y:box.height/2}});
   if(linked) {
     await screen.getByText(target.title,{exact:true}).waitFor({timeout:60000});
     await screen.getByText('Loading image…',{exact:true}).first().waitFor({state:'hidden',timeout:60000});
   }
   results.push(await screen.getByText(target.title,{exact:true}).isVisible());
   await app.screenshot(`mobile-${target.kind}-after-click`);
 }
 await expect(results).toEqual([true,true]);
});
