import { writeFile, readFile } from 'node:fs/promises';
import { CommandId, ThreadId } from '@t3tools/contracts';
import { expect } from 'e2e';
import * as Effect from 'effect/Effect';
import { T3_HOME } from '../e2e.config.ts';
import { run } from './shell.ts';
import { rpcClient, runPromise, test, WEB } from './t3.ts';

test('Squash merge removes numbered Copilot credits and keeps human credits', WEB, async ({t3, app, browser, screen}) => {
 const project = await t3.project('merge-credits');
 const exec = async (bin: string, args: string[]) => (await runPromise(run(bin,args,{cwd:project}))).stdout.trim();
 const git = (...args: string[]) => exec('git',args);
 await exec('glab',['api','-X','PUT','projects/89872487','-f','squash_commit_template=%{all_commits}']);
 const branch = `proof-${Date.now()}`;
 await git('config','user.name','Scenario');
 await git('config','user.email','scenario@example.invalid');
 await git('remote','add','origin','https://gitlab.com/julius54/factory-copilot-48837-evidence.git');
 await git('push','origin',`HEAD:${branch}`);
 await git('switch','-c',`${branch}-fix`);
 await writeFile(`${project}/parser.txt`,'Fixed parser\n');
 await git('add','parser.txt');
 await git('commit','-m','Fix parser\n\nCo-authored-by: Claude <noreply@anthropic.com>\nCo-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>\nCo-authored-by: Sam Human <4821+copilot-fan@users.noreply.github.com>');
 await git('push','-u','origin',`${branch}-fix`);
 const mr = JSON.parse(await exec('glab',['api','-X','POST','projects/89872487/merge_requests','-f',`source_branch=${branch}-fix`,'-f',`target_branch=${branch}`,'-f','title=Fix parser']));
 const thread = await t3.thread({project,title:'Inspect merge credits',messages:['Start']});
 await runPromise(Effect.gen(function*(){
 const client = yield* rpcClient(T3_HOME,app.baseUrl ?? '');
 yield* client['orchestration.dispatchCommand']({type:'thread.pull-request.link',commandId:CommandId.make(`link-${branch}`),threadId:ThreadId.make(thread.threadId),host:'gitlab.com',repository:'julius54/factory-copilot-48837-evidence',number:mr.iid,url:mr.web_url,source:'manual'});
 }).pipe(Effect.scoped));
 await browser.setViewport({width:1440,height:1000});
 await t3.open('/settings/source-control');
 await screen.getByRole('switch','Remove agent credits when merging',{exact:true}).tap();
 await app.screenshot('agent-credit-removal-enabled');
 await t3.open(thread);
 await screen.getByRole('button','Toggle right panel',{exact:true}).tap();
 await screen.getByRole('button','Linked items L',{exact:true}).tap();
 await screen.getByRole('link',new RegExp(`^#${mr.iid} Fix parser`)).tap();
 await screen.getByRole('button','More merge request actions',{exact:true}).tap();
 await screen.getByRole('menuitemradio','Squash and merge',{exact:true}).tap();
 await screen.getByRole('button','Squash and merge',{exact:true}).tap();
 await screen.getByRole('button','Confirm merge?',{exact:true}).tap();
 await screen.getByText('Merged',{exact:true}).waitFor({timeout:60000});
 await git('fetch','origin',branch);
 const message = await git('log','-1','--format=%B','FETCH_HEAD^2');
 await screen.getByRole('button','Toggle terminal drawer',{exact:true}).tap();
 const input = screen.getByRole('textbox','Terminal input');
 await browser.locator('[aria-label="Terminal input"][data-workspace-focus-default]').waitFor();
 await input.focus();
 await browser.keyboard.type("PS1='$ '; clear; git log -1 --format=%B FETCH_HEAD^2; touch result-ready\n");
 await expect.poll(() => readFile(`${project}/result-ready`, 'utf8').then(() => true).catch(() => false), {timeout:30000}).toBe(true);
 await app.screenshot('squash-commit-credits');
 expect(message.includes('223556219+Copilot@users.noreply.github.com')).toBe(false);
 expect(message.includes('noreply@anthropic.com')).toBe(false);
 expect(message.includes('Sam Human <4821+copilot-fan@users.noreply.github.com>')).toBe(true);
});
