import { execFileSync } from 'node:child_process';
import { writeFileSync, chmodSync } from 'node:fs';
import { join } from 'node:path';
import { expect } from 'e2e';
import { test, WEB } from './t3.ts';
import { T3_HOME } from '../e2e.config.ts';

test('Ready keeps Marking until the Ready request completes', WEB, async ({t3, app, screen}) => {
  const env = process.env;
  const az = (args: string[]) => execFileSync('/usr/bin/az', args, {env, encoding:'utf8'}).trim();
  const common = ['--org', env.AZURE_DEVOPS_TEST_ORG!, '--project', env.AZURE_DEVOPS_TEST_PROJECT!];
  const tag = `proof-ready-${Date.now()}`;
  const base = `${tag}-base`;
  const feature = `${tag}-feature`;
  const repo = 't3-factory-test';
  const url = `${env.AZURE_DEVOPS_TEST_ORG}/${env.AZURE_DEVOPS_TEST_PROJECT}/_git/${repo}`;
  const project = await t3.project('Ready request proof', {'README.md':'Ready request demonstration\n'});
  const git = (args:string[]) => execFileSync('git',args,{cwd:project,env,encoding:'utf8'});
  const helper = '!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f';
  git(['remote','add','origin',url]);
  git(['branch','-m',base]);
  git(['-c',`credential.helper=${helper}`,'push','origin',base]);
  git(['checkout','-b',feature]);
  writeFileSync(join(project,'change.txt'),'Synthetic change for Ready pending proof\n');
  git(['add','.']);
  git(['-c','user.name=Scenario','-c','user.email=scenario@example.invalid','commit','-m','Demonstrate Ready request']);
  git(['-c',`credential.helper=${helper}`,'push','-u','origin',feature]);
  const pr = JSON.parse(az(['repos','pr','create',...common,'--repository',repo,'--source-branch',feature,'--target-branch',base,'--title','Ready pending label proof','--draft','true','-o','json']));
  try {
    const wrapper = join(T3_HOME,'bin','az');
    writeFileSync(wrapper, `#!/usr/bin/python3\nimport subprocess,sys,time\nr=subprocess.run(['/usr/bin/az']+sys.argv[1:],capture_output=True)\nif '--draft' in sys.argv and 'false' in sys.argv:\n time.sleep(25)\nsys.stdout.buffer.write(r.stdout)\nsys.stderr.buffer.write(r.stderr)\nsys.exit(r.returncode)\n`);
    chmodSync(wrapper,0o755);
    const thread = await t3.thread({project,title:'Ready request proof',messages:['Explain the sample change.']});
    await t3.open(thread);
    await screen.getByRole('button','Ready',{exact:true}).waitFor({timeout:120000});
    await app.screenshot('ready-before-click');
    await screen.getByRole('button','Ready',{exact:true}).tap();
    await new Promise(resolve => setTimeout(resolve,3000));
    await app.screenshot('ready-request-pending');
    const pending = screen.getByRole('button',/^(Marking|Merging)\.\.\.$/);
    await expect(pending).toHaveText('Marking...');
    await expect(pending).toBeDisabled();
    await screen.getByRole('button','Merge',{exact:true}).waitFor({timeout:60000});
    await app.screenshot('ready-request-finished');
    await expect(screen.getByRole('button','Merge',{exact:true})).toBeEnabled();
  } finally {
    az(['repos','pr','update','--id',String(pr.pullRequestId),'--org',env.AZURE_DEVOPS_TEST_ORG!,'--status','abandoned','-o','none']);
    git(['-c',`credential.helper=${helper}`,'push','origin','--delete',feature,base]);
  }
});
