import { test, expect } from '@playwright/test';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = dirname(fileURLToPath(import.meta.url));

test.describe('Apple USDZ Files', () => {
  test('loads Apple official USDZ file (toy_biplane)', async ({ page }) => {
    await page.goto('/');
    await page.locator('canvas').first().waitFor({ state: 'visible', timeout: 10000 });

    // Load the Apple USDZ file
    await page.locator('#file-input').setInputFiles(
      resolve(__dirname, '../fixtures/toy_biplane_realistic.usdz')
    );

    // Collect console messages for debugging
    const consoleMessages: string[] = [];
    page.on('console', msg => consoleMessages.push(`[${msg.type()}] ${msg.text()}`));

    // Wait for loading (WASM module init + USDC parsing can be very slow for large files)
    // Monitor status bar for completion
    try {
      await page.waitForFunction(() => {
        const status = document.querySelector('[data-testid="status-message"]');
        const toast = document.querySelector('[data-testid="error-toast"]');
        const vcount = document.querySelector('[data-testid="vertex-count"]');
        return (status?.textContent?.includes('Loaded') || status?.textContent?.includes('failed') ||
                toast !== null || (vcount && !vcount.textContent?.includes('0')));
      }, { timeout: 30000 });
    } catch {
      // Timeout is acceptable — file may still be loading
    }
    await page.waitForTimeout(2000); // Extra buffer for toast rendering

    // Check results
    const vertexCount = page.locator('[data-testid="vertex-count"]');
    const errorToast = page.locator('[data-testid="error-toast"]');

    const hasVertices = await vertexCount.isVisible().catch(() => false);
    const hasError = await errorToast.isVisible().catch(() => false);

    // Print console messages for debugging
    const usdRelated = consoleMessages.filter(m => m.toLowerCase().includes('usd') || m.toLowerCase().includes('error') || m.toLowerCase().includes('fail'));
    if (usdRelated.length > 0) console.log('Console messages:', usdRelated.join('\n'));

    if (hasVertices) {
      const text = await vertexCount.textContent();
      console.log('SUCCESS: Apple USDZ loaded! Vertices:', text);
      expect(text).not.toContain('V: 0');
    } else if (hasError) {
      const errorText = await errorToast.textContent();
      console.log('ERROR TOAST:', errorText?.substring(0, 300));
      // Verify error message mentions USDZ and conversion
      expect(errorText!.toLowerCase()).toMatch(/usdz|usdc|convert|blender|glb/i);
    } else {
      console.log('No response visible - USDZ processing may still be in progress');
    }
    // Test passes as long as we get either success or informative error
    expect(hasVertices || hasError).toBe(true);
  });
});
