/// <reference types="node" />

import { existsSync } from 'node:fs';
import { basename } from 'node:path';
import { expect, test } from '@playwright/test';

const mediaPath = process.env.AV_TOOLS_LARGE_MEDIA;

test('plays a recognized large local video while inspection continues', async ({
  page,
}) => {
  test.skip(
    !mediaPath || !existsSync(mediaPath),
    'Set AV_TOOLS_LARGE_MEDIA to a local video for this opt-in evidence run.'
  );
  test.setTimeout(360_000);
  await page.goto('/');

  const startedAt = Date.now();
  await page
    .locator('input[type="file"][accept*="audio"]')
    .first()
    .setInputFiles(mediaPath as string);
  const name = basename(mediaPath as string);
  const card = page.locator('.media-card').filter({ hasText: name });
  const preview = page.locator('.preview video');
  await expect(preview).toBeVisible({ timeout: 15_000 });
  const previewVisibleMilliseconds = Date.now() - startedAt;
  expect(previewVisibleMilliseconds).toBeLessThan(15_000);
  await expect(card.locator('.phase--probing')).toBeVisible();

  const elementIdentity = await preview.evaluate((element) => {
    element.dataset.evidenceIdentity = crypto.randomUUID();
    return element.dataset.evidenceIdentity;
  });
  await preview.evaluate(async (element) => {
    const video = element as HTMLVideoElement;
    video.muted = true;
    await video.play();
  });
  await expect
    .poll(
      () =>
        preview.evaluate(
          (element) => (element as HTMLVideoElement).currentTime
        ),
      {
        timeout: 15_000,
      }
    )
    .toBeGreaterThan(0);

  await expect(card.locator('.phase--ready')).toBeVisible({
    timeout: 330_000,
  });
  await expect(preview).toHaveAttribute(
    'data-evidence-identity',
    elementIdentity
  );
  await expect(page.getByRole('alert')).toHaveCount(0);
});
