import { expect } from 'e2e';
import * as Effect from 'effect/Effect';
import { readFileSync, writeFileSync, watch } from 'node:fs';
import { ThreadId, DEFAULT_TERMINAL_ID } from '@t3tools/contracts';
import { APP_DIR, T3_HOME } from '../e2e.config.ts';
import { run } from './shell.ts';
import { rpcClient, runPromise, test, WEB } from './t3.ts';

test('Git Unicode remote names survive checkout, identity, status and publishing', WEB, async ({ t3, app, browser, screen }) => {
  const cwd = await t3.project('unicode-remotes');
  const git = (args: string[]) => runPromise(run('git', args, { cwd }));
  await git(['remote', 'add', 'origin', 'https://github.com/octocat/Hello-World.git']);
  await git(['fetch', '--quiet', 'origin', 'master']);
  await git(['reset', '--hard', 'FETCH_HEAD']);
  await git(['remote', 'add', '1hailong123\u00a0', 'https://github.com/1hailong123/Hello-World.git']);
  const thread = await t3.thread({ project: cwd, title: 'Unicode Git remote evidence', messages: ['hello'], model: 'default' });
  await browser.emulateMedia({ colorScheme: 'dark' });
  await t3.open(thread);
  await screen.getByRole('button', 'New thread in unicode-remotes', { exact: true }).tap();
  const origin = app.baseUrl ?? '';
  const branch = browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first();
  await branch.tap();
  await screen.getByPlaceholder('Search refs...').fill('#11816');
  await screen.getByRole('option', /Checkout pull request/).tap();
  await browser.locator('button:not([disabled])').filter({ hasText: /^Local$/ }).waitFor();
  await app.screenshot('pr-checkout-ready');
  await screen.getByRole('button', 'Local', { exact: true }).tap();
  await screen.getByRole('dialog').waitFor({ state: 'hidden' });
  await app.screenshot('pr-checkout-complete');
  const remoteOutput = (await git(['remote'])).stdout;
  const upstream = (await git(['rev-parse', '--abbrev-ref', '@{upstream}'])).stdout.trim();
  const checkoutReport = ['CHECKOUT real PR octocat/Hello-World#11816 (Local)', 'Expected: reuse 1hailong123<U+00A0>, add no remote.', 'Remotes: ' + remoteOutput.trimEnd().replaceAll('\u00a0', '<U+00A0>').split('\n').join(', '), 'Upstream: ' + upstream.replaceAll('\u00a0', '<U+00A0>')].join('\n');
  await t3.open(thread);
  const probeCwd = await t3.project('runtime-remotes');
  const probePath = new URL('./unicode-remote-runtime.ts', import.meta.url).pathname;
  const resultPath = `${probeCwd}/runtime-results.txt`;
  const probe = await runPromise(run(process.execPath, [probePath, APP_DIR, probeCwd, resultPath]));
  const result = JSON.parse(probe.stdout.trim().split('\n').at(-1)!);
  const report = checkoutReport + '\n\n' + readFileSync(resultPath, 'utf8');
  writeFileSync(`${cwd}/remote-evidence.txt`, report);
  await runPromise(Effect.gen(function*() {
    const client = yield* rpcClient(T3_HOME, origin);
    yield* client['terminal.open']({ threadId: ThreadId.make(thread.threadId), terminalId: DEFAULT_TERMINAL_ID, cwd, cols: 120, rows: 28 });
  }).pipe(Effect.scoped));
  await screen.getByRole('button', 'Toggle terminal drawer').tap();
  const drawer = await browser.evaluate(() => { const r = document.querySelector('[data-thread-terminal-drawer]')!.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + 2 }; });
  await browser.mouse.move(drawer.x, drawer.y);
  await browser.mouse.down();
  await browser.mouse.move(drawer.x, 320);
  await browser.mouse.up();
  const terminal = screen.getByLabel('Terminal input');
  await terminal.waitFor();
  const terminalDone = new Promise<void>((resolve) => { const watcher = watch(cwd, (_, filename) => { if (filename === '.evidence-ready') { watcher.close(); resolve(); } }); });
  await terminal.focus();
  await browser.keyboard.type("PS1='' ; clear ; cat remote-evidence.txt ; printf '\\033[?25l' ; touch .evidence-ready");
  await browser.keyboard.press('Enter');
  await terminalDone;
  await app.screenshot('unicode-remote-all-behaviors');
  expect({ remotes: remoteOutput.split('\n').filter(Boolean), upstream, identity: result.identities, locatorNames: result.locatorNames, hasRemote: result.hasRemote, pushed: result.pushed, received: result.received }).toEqual({ remotes: ['1hailong123\u00a0', 'origin'], upstream: '1hailong123\u00a0/feature/learn-pr', identity: ['github.com/octocat/hello-world', 'github.com/octocat/hello-world'], locatorNames: ['\u00a0', '\u00a0'], hasRemote: true, pushed: true, received: true });
});
