import {
  Body,
  Controller,
  Get,
  Param,
  Post,
  Query,
  Res,
} from '@nestjs/common';
import type { Response } from 'express';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { Permission } from '@pac/types';
import { RequirePermission } from '../../common/decorators/permissions.decorator';
import {
  TenantScope,
  TenantScopeContext,
} from '../../common/decorators/tenant-scope.decorator';
import { PlanScriptOrchestrator } from '../ai/orchestrators/plan-script.orchestrator';
import { PlanSummaryOrchestrator } from '../ai/orchestrators/plan-summary.orchestrator';
import { PlanAggregateService } from './plan-aggregate.service';

/**
 * PlansAggregateController — 生产路径的 plan 详情聚合 + AI 资产再生成端点。
 *
 * 端点(全 /pac/v1/plans/:id/...):
 *   GET  :id/full              详情聚合(plan+patient+profile+persona+chains+facts)
 *   POST :id/script:regenerate 同步重生成话术(测试用,等价 stream 但不流)
 *   GET  :id/script:stream     流式重生成话术(SSE)
 *   GET  :id/summary:stream    流式重生成 plan 摘要(SSE,1 次产 3 段)
 *
 * 跟 PlanController(同 /plans 前缀,strict Zod 的 CRUD)分工:
 *   - PlanController:list / detail / assign / recycle / executions(都走 strict Zod 契约)
 *   - 本控制器:聚合 + AI 资产相关(响应 shape 复杂,跳过 strict Zod 提速迭代)
 *
 * 放 PlanAggregateModule:避免 PlanModule ↔ PlanAggregateModule 循环依赖(PlanAggregateModule 已 import PlanModule/AiModule)。
 */
@ApiTags('plan')
@ApiBearerAuth('accessToken')
@Controller('plans')
export class PlansAggregateController {
  constructor(
    private readonly demo: PlanAggregateService,
    private readonly planScript: PlanScriptOrchestrator,
    private readonly planSummary: PlanSummaryOrchestrator,
  ) {}

  // ─────────────────────────────────────────────
  // 详情聚合
  // ─────────────────────────────────────────────

  @Get(':id/full')
  @RequirePermission(Permission.PLAN_VIEW_OWN)
  @ApiOperation({
    summary: 'Plan 详情聚合(plan+patient+profile+persona+chains+facts)',
    description: '前端 (app)/plans/[planId] 用本端点;PlanController.detail 走 strict Zod 给外部。',
  })
  getFull(@TenantScope() scope: TenantScopeContext, @Param('id') planId: string) {
    return this.demo.getPlanDetailByPlanId(scope, planId);
  }

  // ─────────────────────────────────────────────
  // 话术 — 同步重生成 / 流式重生成
  // ─────────────────────────────────────────────

  @Post(':id/script:regenerate')
  @RequirePermission(Permission.PLAN_VIEW_OWN)
  @ApiOperation({ summary: '重新生成 plan 话术(测试 / 调试用,输入不变)' })
  async regenerateScript(
    @Param('id') planId: string,
    @Query('bustCache') bustCache?: string,
    @Query('model') model?: string,
    @Body() body?: { dryRun?: boolean },
  ) {
    const result = await this.planScript.generate(planId, {
      bustCache: bustCache === 'true' || bustCache === '1',
      modelIdOverride: model,
      dryRun: body?.dryRun ?? false,
    });
    return {
      planId: result.planId,
      planScriptId: result.planScriptId,
      agentInvocationId: result.agentInvocationId,
      source: result.source,
      cacheHit: result.cacheHit,
      costYuan: result.costYuan,
      content: result.content,
      structured: result.structured,
    };
  }

  /**
   * 流式重生成话术 — SSE。
   *
   * 事件 data 是 JSON,见 PlanScriptStreamEvent:
   *   start    {invocationId, modelId, promptVersion}
   *   partial  {structured, sections}        ← 多次
   *   done     {planScriptId, source, content, sections, costYuan}
   *   error    {message}
   *
   * 用裸 Response 而不是 @Sse() Observable — 后者把 finalize 时机藏起来。
   */
  @Get(':id/script:stream')
  @RequirePermission(Permission.PLAN_VIEW_OWN)
  @ApiOperation({ summary: '流式重新生成 plan 话术(SSE)' })
  async streamScript(
    @Param('id') planId: string,
    @Query('model') model: string | undefined,
    @Res() res: Response,
  ): Promise<void> {
    await this.pipeSse(res, this.planScript.generateStream(planId, { modelIdOverride: model }));
  }

  // ─────────────────────────────────────────────
  // Summary — 流式重生成(1 次产 3 段:onePage / medicalRecord / treatmentChain)
  // ─────────────────────────────────────────────

  @Get(':id/summary:stream')
  @RequirePermission(Permission.PLAN_VIEW_OWN)
  @ApiOperation({ summary: '流式重新生成 plan 摘要(SSE,1 次产 3 段)' })
  async streamSummary(
    @Param('id') planId: string,
    @Query('model') model: string | undefined,
    @Res() res: Response,
  ): Promise<void> {
    await this.pipeSse(res, this.planSummary.generateStream(planId, { modelIdOverride: model }));
  }

  // ─────────────────────────────────────────────
  // 内部:把 AsyncGenerator → SSE 写出(共用,两个流式端点都走)
  // ─────────────────────────────────────────────

  private async pipeSse<T extends { type: string }>(
    res: Response,
    stream: AsyncIterable<T>,
  ): Promise<void> {
    res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
    res.setHeader('Cache-Control', 'no-cache, no-transform');
    res.setHeader('Connection', 'keep-alive');
    res.setHeader('X-Accel-Buffering', 'no'); // 关 nginx buffering
    res.flushHeaders?.();

    // 心跳防代理断连(每 15s 一个注释行)
    const heartbeat = setInterval(() => res.write(': hb\n\n'), 15_000);

    try {
      for await (const evt of stream) {
        res.write(`event: ${evt.type}\n`);
        res.write(`data: ${JSON.stringify(evt)}\n\n`);
        const r = res as Response & { flush?: () => void };
        r.flush?.();
        if (evt.type === 'done' || evt.type === 'error') break;
      }
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      res.write(`event: error\ndata: ${JSON.stringify({ type: 'error', message })}\n\n`);
    } finally {
      clearInterval(heartbeat);
      res.end();
    }
  }
}
