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 { z } from 'zod';
import { RequirePermission } from '../../common/decorators/permissions.decorator';
import {
  TenantScope,
  TenantScopeContext,
} from '../../common/decorators/tenant-scope.decorator';
import {
  CurrentUser,
  AuthenticatedUser,
} from '../../common/decorators/current-user.decorator';
import { PrismaService } from '../../prisma/prisma.service';
import { PlanScriptOrchestrator } from '../ai/orchestrators/plan-script.orchestrator';
import { PlanSummaryOrchestrator } from '../ai/orchestrators/plan-summary.orchestrator';
import { PlanAggregateService } from './plan-aggregate.service';

const ScriptFeedbackSchema = z.object({
  feedback: z.enum(['up', 'down']),
});

/**
 * 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,
    private readonly prisma: PrismaService,
  ) {}

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

  @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)
  // ─────────────────────────────────────────────

  // ─────────────────────────────────────────────
  // 话术 / 摘要 thumbs up/down 反馈("本段是否好用")
  // ─────────────────────────────────────────────

  /**
   * 反馈某 plan 当前话术(对应 plan_scripts.agent_invocation_id)up/down。
   * 同一 invocation 反复点会覆盖(再点 down 覆盖 up,以最新为准)。
   * 没找到 planScript / agentInvocationId → 404(避免无 invocation 的 plan 接受反馈)。
   *
   * 后续可加:summary feedback(对称端点)/ 聚合 dashboard(up/down 比 + 命中 fallback 时禁止评)。
   */
  @Post(':id/script-feedback')
  @RequirePermission(Permission.PLAN_VIEW_OWN)
  @ApiOperation({ summary: '对当前话术 thumbs up/down 反馈("本段是否好用")' })
  async submitScriptFeedback(
    @TenantScope() scope: TenantScopeContext,
    @CurrentUser() user: AuthenticatedUser,
    @Param('id') planId: string,
    @Body() body: unknown,
  ) {
    const { feedback } = ScriptFeedbackSchema.parse(body);
    const script = await this.prisma.planScript.findFirst({
      where: { planId, hostId: scope.hostId, tenantId: scope.tenantId },
    });
    if (!script?.agentInvocationId) {
      return { ok: false as const, reason: 'no_invocation' };
    }
    await this.prisma.agentInvocation.update({
      where: { id: script.agentInvocationId },
      data: {
        userFeedback: feedback,
        userFeedbackAt: new Date(),
        userFeedbackBy: user.sub,
      },
    });
    return { ok: true as const, invocationId: script.agentInvocationId, feedback };
  }

  @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();
    }
  }
}
