import { Logger } from '@nestjs/common';
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Job } from 'bullmq';
import { QueueName } from '../queue-names';
import type { PlanAssetGenerateJob } from '../job-payloads';

/**
 * plan-asset-generate worker — ⚠️ 故意 stub 不调 AI(W2-W3 阶段省 token)。
 *
 * 触发链(自动路径,目前 stub):
 *   plan-recompute 完 → 每个新 plan enqueue → 本 worker 只 log,不真生成
 *
 * 真实生成走"手动按钮"路径(避免 token 失控):
 *   - 详情页 "重新生成话术" 按钮 → POST /pac/v1/plans/:id/script:regenerate (sync)
 *   - 详情页 "重新生成摘要" 按钮 → POST /pac/v1/plans/:id/summary:regenerate (sync)
 *   - 详情页打开自动拉流式 → GET /pac/v1/plans/:id/script:stream (SSE)
 *
 * 如何启用自动 AI 生成(W4+ 真实数据演示时):
 *   1. 设环境变量 PLAN_ASSET_AUTO_GENERATE=true
 *   2. 取消下面的 stub 返回,启用真实 ScriptOrchestrator + SummaryOrchestrator 调用
 *   3. 失败兜底走 template_fallback(plan_scripts.source='template_fallback')
 *
 * 当前观察方式:Bull Board 看 completed 队列,确认 "would generate" 都被记录。
 */
@Processor(QueueName.PLAN_ASSET_GENERATE, { concurrency: 2 })
export class PlanAssetGenerateProcessor extends WorkerHost {
  private readonly logger = new Logger(PlanAssetGenerateProcessor.name);

  async process(job: Job<PlanAssetGenerateJob>): Promise<{
    ok: boolean;
    skipped: true;
    reason: string;
  }> {
    const { hostId, tenantId, planId, assets, triggeredBy } = job.data;
    const wanted = assets?.join('+') ?? 'script+summary';

    this.logger.log(
      `[STUB · no-AI] plan-asset-generate plan=${planId.slice(0, 8)} ` +
        `wanted=${wanted} triggeredBy=${triggeredBy} ` +
        `host=${hostId.slice(0, 8)} tenant=${tenantId}`,
    );

    // TODO: 启用真实生成(set PLAN_ASSET_AUTO_GENERATE=true)
    // const tasks: Promise<unknown>[] = [];
    // if (!assets || assets.includes('script'))
    //   tasks.push(this.scriptOrchestrator.generate(planId).catch(err => fallbackScript(planId, err)));
    // if (!assets || assets.includes('summary'))
    //   tasks.push(this.summaryOrchestrator.generate(planId).catch(err => fallbackSummary(planId, err)));
    // await Promise.all(tasks);

    return {
      ok: true,
      skipped: true,
      reason: 'W2-W3 token-saving stub; use 详情页"重新生成"按钮触发真实 AI',
    };
  }
}
