import {Injectable, signal} from '@angular/core';

export type GpuTier = 'webgpu' | 'webgl' | 'none';

@Injectable({providedIn: 'root'})
export class GpuCapabilityService {
  private cachedTier: GpuTier | null = null;
  readonly tier = signal<GpuTier | null>(null);

  async detect(): Promise<GpuTier> {
    if (this.cachedTier) {
      return this.cachedTier;
    }

    const result = await this.probe();
    this.cachedTier = result;
    this.tier.set(result);
    return result;
  }

  private async probe(): Promise<GpuTier> {
    if (await this.isWebGpuAvailable()) {
      return 'webgpu';
    }

    if (this.isWebGlAvailable()) {
      return 'webgl';
    }

    return 'none';
  }

  private async isWebGpuAvailable(): Promise<boolean> {
    if (!navigator.gpu) {
      return false;
    }

    try {
      const adapter = await navigator.gpu.requestAdapter();
      return adapter !== null;
    } catch {
      return false;
    }
  }

  private isWebGlAvailable(): boolean {
    try {
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('webgl2');
      return context !== null;
    } catch {
      return false;
    }
  }
}
