import { type GenerationResult, generateSpec as sharedGenerate } from '@bmm/llm';
import { config } from '../config.js';

export type { GenerationResult };

/**
 * Build-worker spec generation (cache-miss path). Runs async in a BullMQ
 * worker — no proxy timeout. Defaults to GLM to keep this rare path cheap;
 * falls back to Anthropic Sonnet on GLM failure so a temporary outage at one
 * provider doesn't break builds.
 */
export async function generateSpec(prompt: string): Promise<GenerationResult> {
  if (config.GLM_API_KEY) {
    try {
      return await sharedGenerate(prompt, {
        provider: 'glm',
        glmApiKey: config.GLM_API_KEY,
        model: config.MODEL_GENERATE,
        maxTokens: 8192,
        timeoutMs: 180_000,
      });
    } catch (err) {
      console.warn(
        '[generator] GLM failed, falling back to Anthropic Sonnet:',
        (err as Error).message,
      );
    }
  }
  if (!config.ANTHROPIC_API_KEY) {
    // No keys at all → @bmm/llm returns mockSpec, which keeps builds working
    // in dev without any provider configured.
    return sharedGenerate(prompt, { provider: 'anthropic' });
  }
  return sharedGenerate(prompt, {
    provider: 'anthropic',
    apiKey: config.ANTHROPIC_API_KEY,
    model: 'claude-sonnet-4-6',
    maxTokens: 8192,
  });
}
