import { Injectable, inject } from '@angular/core';
import { ElectronBridgeService } from '../../../core/platform/electron/electron-bridge.service';
import type { LocalPluginDiscoveryResult, LocalPluginManifestDescriptor } from '../domain/models/plugin-runtime.models';

@Injectable({ providedIn: 'root' })
export class LocalPluginDiscoveryService {
  private readonly electronBridge = inject(ElectronBridgeService);

  get isAvailable(): boolean {
    return this.electronBridge.isAvailable;
  }

  async getPluginsPath(): Promise<string | null> {
    const api = this.electronBridge.getApi();

    return api ? await api.getLocalPluginsPath() : null;
  }

  async discoverManifests(): Promise<LocalPluginDiscoveryResult> {
    const api = this.electronBridge.getApi();

    if (!api) {
      return {
        errors: [],
        plugins: [],
        pluginsPath: ''
      };
    }

    const result = await api.listLocalPluginManifests();

    return {
      errors: result.errors,
      plugins: result.plugins.map((plugin): LocalPluginManifestDescriptor => ({
        discoveredAt: plugin.discoveredAt,
        entrypointPath: plugin.entrypointPath,
        pluginRootUrl: plugin.pluginRootUrl,
        manifest: plugin.manifest,
        manifestPath: plugin.manifestPath,
        pluginRoot: plugin.pluginRoot,
        readmePath: plugin.readmePath
      })),
      pluginsPath: result.pluginsPath
    };
  }
}
