/**
 * Plugin registration and lifecycle management.
 */

import type { TSTree } from "../scanner/parser";
import type { GraphEdge, GraphNode } from "../types";
import type { PatternPlugin } from "./base";
import { CBSSchemaPlugin } from "./cbs-schema";
import { ConstantPoolPlugin } from "./constant-pool";
import { EJBComponentPlugin } from "./ejb-component";

export class PluginRegistry {
  private _plugins: PatternPlugin[] = [];

  register(plugin: PatternPlugin): void {
    this._plugins.push(plugin);
    console.log(`[plugin.registered] ${plugin.name}`);
  }

  registerDefaults(): void {
    this.register(new CBSSchemaPlugin());
    this.register(new EJBComponentPlugin());
    this.register(new ConstantPoolPlugin());
  }

  get plugins(): PatternPlugin[] {
    return [...this._plugins];
  }

  runPlugins(tree: TSTree, filePath: string): (GraphNode | GraphEdge)[] {
    const results: (GraphNode | GraphEdge)[] = [];
    for (const plugin of this._plugins) {
      try {
        if (plugin.matches(tree, filePath)) {
          const extracted = plugin.extract(tree, filePath);
          results.push(...extracted);
        }
      } catch (e) {
        console.error(
          `[plugin.failed] ${plugin.name} on ${filePath}: ${e instanceof Error ? e.message : e}`,
        );
      }
    }
    return results;
  }
}
