import { type BuildStrategyHooks, resolveBuildStrategy } from "./build.ts";
import type { BuildArtifact, BuildStrategy } from "./build-strategy.ts";

/**
 * Meta-strategy that auto-detects the appropriate framework build strategy and
 * delegates to it. Detection runs in registry order with bun as the universal
 * fallback, so a buildable strategy always resolves. Use `resolveBuildStrategy`
 * directly when the resolved build type is also needed.
 */
export class AutoBuild implements BuildStrategy {
  readonly #appPath: string;
  readonly #entrypoint?: string;
  readonly #hooks: BuildStrategyHooks;

  constructor(
    options: { appPath: string; entrypoint?: string } & BuildStrategyHooks,
  ) {
    this.#appPath = options.appPath;
    this.#entrypoint = options.entrypoint;
    this.#hooks = {
      io: options.io,
      requireStandalone: options.requireStandalone,
    };
  }

  async canBuild(_signal?: AbortSignal): Promise<boolean> {
    // Detection always resolves (bun is the universal fallback).
    return true;
  }

  async execute(signal?: AbortSignal): Promise<BuildArtifact> {
    const { strategy } = await resolveBuildStrategy({
      appPath: this.#appPath,
      entrypoint: this.#entrypoint,
      buildType: "auto",
      signal,
      ...this.#hooks,
    });
    return strategy.execute(signal);
  }
}
