/// <reference lib="dom" />
import * as fs from 'node:fs/promises';
import { watchFile, unwatchFile } from 'node:fs';
import { expect } from 'e2e';
import { run } from './shell.ts';
import { test, WEB, runPromise, makeState } from './t3.ts';
import { T3_HOME } from '../e2e.config.ts';

const PR = 'https://github.com/octocat/Spoon-Knife/pull/42453';
const BRANCH = 't3code/pr-42453/fix/edit-judul';
const untilFile = async (file: string) => {
  try { await fs.stat(file); return; } catch {}
  await new Promise<void>((resolve) => {
    watchFile(file, { interval: 100 }, (stat) => {
      if (stat.nlink) { unwatchFile(file); resolve(); }
    });
  });
};

test('A PR checkout keeps typed text and an early send uses its worktree through both entry points', WEB,
 async ({t3, app, browser, screen}) => {
  await browser.setViewport({width:1280,height:800});
  await browser.emulateMedia({colorScheme:'dark'});
  const observations: Array<{entry:string; typed:boolean; waited?:boolean; branch:boolean; sameDraft:boolean}> = [];
  for (const entry of ['detail-panel', 'prompt-link']) {
    const project = await t3.project(entry === 'detail-panel' ? 'PR panel review' : 'PR link review');
    const git = (args: string[]) => runPromise(run('git', args, {cwd: project}));
    await git(['remote','add','origin','https://github.com/octocat/Spoon-Knife.git']);
    await git(['fetch','--depth=1','origin','main']);
    await git(['reset','--hard','origin/main']);
    const started = `${project}/.git/checkout-started`;
    const release = `${project}/.git/release-checkout`;
    const finished = `${project}/.git/checkout-finished`;
    await fs.writeFile(`${project}/.git/hooks/post-checkout`, `#!/bin/sh\ntouch '${started}'\nwhile [ ! -f '${release}' ]; do sleep 0.1; done\ntouch '${finished}'\n`, {mode:0o755});
    const thread = await t3.thread({project,title:`Earlier ${entry} work`,messages:['Start'],model:'multi-turn'});
    await t3.open(thread);
    if (entry === 'detail-panel') {
      await app.open(`/pull-requests?repository=octocat%2FSpoon-Knife&number=42453`);
      await screen.getByRole('button','Check out',{exact:true}).tap();
      await screen.getByRole('menuitem',/^In a separate worktree/).tap();
    } else {
      await app.open(`/new?pr=${encodeURIComponent(PR)}`);
      await screen.getByRole('button','Check out',{exact:true}).tap();
    }
    await untilFile(started);
    const textbox = screen.getByRole('textbox');
    await textbox.fill(`Review this pull request please (${entry})`);
    const draftUrl = await browser.evaluate(() => location.pathname + location.search);
    await app.screenshot(`${entry}-typed-during-checkout`);
    let waited: boolean | undefined;
    if (entry === 'prompt-link') {
      await textbox.press('Enter');
      // Capture the pending send while the actual git hook still holds the checkout.
      await app.screenshot(`${entry}-sent-before-checkout-finishes`);
      const threads = await runPromise(makeState(T3_HOME).cli(['thread','list','--project',project,'--json']));
      waited = JSON.parse(threads.stdout).length === 1;
    }
    await fs.writeFile(release,'go');
    await untilFile(finished);
    // The success toast is emitted after rebinding (or opening the second draft on base).
    await screen.getByText(/Checked out|Ready to review|already checked out/i).first().waitFor({timeout:60000});
    await app.screenshot(`${entry}-checkout-complete`);
    const visibleBranch = await browser.evaluate(() => [...document.querySelectorAll('[data-slot="combobox-trigger"][aria-label^="Branch:"]')].find(e => e.getBoundingClientRect().width > 0)?.getAttribute('aria-label'));
    const currentUrl = await browser.evaluate(() => location.pathname + location.search);
    const typed = entry === 'detail-panel' ? (await textbox.textContent())?.includes(`Review this pull request please (${entry})`) === true : true;
    let correctBranch = visibleBranch?.includes(BRANCH) === true;
    if (entry === 'detail-panel') {
      if (draftUrl !== currentUrl) await app.open(draftUrl);
      await screen.getByRole('textbox').waitFor();
      await screen.getByText('Review this pull request please (detail-panel)',{exact:true}).first().waitFor();
      await app.screenshot('detail-panel-original-draft-after-checkout');
    }
    if (entry === 'prompt-link') {
      let sent: {threadId:string} | undefined;
      for (let attempt = 0; attempt < 30 && !sent; attempt++) {
        const listed = await runPromise(makeState(T3_HOME).cli(['thread','list','--project',project,'--json']));
        sent = JSON.parse(listed.stdout).find((row: {threadId:string}) => row.threadId !== thread.threadId);
      }
      if (!sent) throw new Error('The sent prompt did not produce a thread');
      await t3.open(sent);
      await screen.getByText(`Review this pull request please (${entry})`,{exact:true}).first().waitFor({timeout:60000});
      await screen.getByText('This turn is a replay.',{exact:false}).first().waitFor({timeout:60000});
      await screen.getByRole('button','Stop generation').waitFor({state:'hidden',timeout:60000});
      await screen.getByText(/Syncing messages/).waitFor({state:'hidden',timeout:60000});
      await browser.evaluate(() => {
        const viewport = document.querySelector<HTMLElement>('[data-assistant-citation-viewport]');
        if (viewport) viewport.scrollTop = 0;
        return null;
      });
      await screen.getByText(`Review this pull request please (${entry})`,{exact:true}).first().waitFor();
      await app.screenshot(`${entry}-sent-thread-workspace`);
      const shown = await runPromise(makeState(T3_HOME).cli(['thread','show',sent.threadId,'--json']));
      const data = JSON.parse(shown.stdout);
      correctBranch = data.thread.branch === BRANCH && data.thread.worktreePath !== null;
    }
    observations.push({entry,typed,waited,branch:correctBranch,sameDraft:entry==='prompt-link'||draftUrl===currentUrl});
  }
  expect(observations).toEqual([
    {entry:'detail-panel',typed:true,waited:undefined,branch:true,sameDraft:true},
    {entry:'prompt-link',typed:true,waited:true,branch:true,sameDraft:true},
  ]);
 });
