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, SubmitRecallFeedbackRequestSchema } 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 { RecallSummaryOrchestrator } from '../ai/orchestrators/recall-summary.orchestrator';
import { PersonaSummaryOrchestrator } from '../ai/orchestrators/persona-summary.orchestrator';
import { RecallBriefOrchestrator } from '../ai/orchestrators/recall-brief.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 recallSummary: RecallSummaryOrchestrator,
    private readonly personaSummary: PersonaSummaryOrchestrator,
    private readonly recallBrief: RecallBriefOrchestrator,
    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);
  }

  // 回访历史「一句话摘要」get-or-generate(详情页回访历史卡进卡片即调:
  //   有 ready 摘要秒回;没有则当场跑 AiCall 生成存库再回;无回访记录 → status='empty')。
  @Get(':id/recall-summary')
  @RequirePermission(Permission.PLAN_VIEW_OWN)
  @ApiOperation({ summary: '回访历史一句话摘要(有则取、无则当场生成)' })
  getRecallSummary(@TenantScope() scope: TenantScopeContext, @Param('id') planId: string) {
    return this.recallSummary.getOrGenerate(scope, planId);
  }

  // 画像标签「一句话重点」get-or-generate(详情页「画像标签」卡进卡片即调:
  //   有 ready 摘要秒回;没有则当场跑 AiCall 生成存库再回;无 persona/feature → status='empty')。
  @Get(':id/persona-summary')
  @RequirePermission(Permission.PLAN_VIEW_OWN)
  @ApiOperation({ summary: '画像标签一句话重点(有则取、无则当场生成)' })
  getPersonaSummary(@TenantScope() scope: TenantScopeContext, @Param('id') planId: string) {
    return this.personaSummary.getOrGenerate(scope, planId);
  }

  // 本次召回「一句话简报」get-or-generate(详情页「参考话术」标题下;输入=召回原因+历史治疗+画像,
  //   回答 患者是谁 / 帮其解决什么问题 / 邀约到诊做什么 三问;无召回原因 → status='empty')。
  @Get(':id/recall-brief')
  @RequirePermission(Permission.PLAN_VIEW_OWN)
  @ApiOperation({ summary: '本次召回一句话简报(有则取、无则当场生成)' })
  getRecallBrief(@TenantScope() scope: TenantScopeContext, @Param('id') planId: string) {
    return this.recallBrief.getOrGenerate(scope, planId);
  }

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

  @Post(':id/script:regenerate')
  @RequirePermission(Permission.PLAN_VIEW_OWN)
  @ApiOperation({ summary: '重新生成 plan 话术(测试 / 调试用,输入不变)' })
  async regenerateScript(
    @CurrentUser() user: AuthenticatedUser,
    @Param('id') planId: string,
    @Query('bustCache') bustCache?: string,
    @Query('model') model?: string,
    @Query('tier') tier?: string,
    @Body() body?: { dryRun?: boolean },
  ) {
    const result = await this.planScript.generate(planId, {
      bustCache: bustCache === 'true' || bustCache === '1',
      modelIdOverride: model,
      tier: parseScriptTier(tier),
      dryRun: body?.dryRun ?? false,
      agent: this.resolveAgent(user),
    });
    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(
    @CurrentUser() user: AuthenticatedUser,
    @Param('id') planId: string,
    @Query('model') model: string | undefined,
    @Query('tier') tier: string | undefined,
    @Res() res: Response,
  ): Promise<void> {
    await this.pipeSse(res, (signal) =>
      this.planScript.generateStream(planId, {
        modelIdOverride: model,
        tier: parseScriptTier(tier),
        agent: this.resolveAgent(user),
        signal,
      }),
    );
  }

  /** 当前登录客服 → 自报家门用的 {岗位称呼, 姓名}。
   *  roleTitle:患者侧称呼(员工/管理员→客服;主管→客服主管);name:dictionary.users[sub](无则 null)。 */
  private resolveAgent(user: AuthenticatedUser): { name: string | null; roleTitle: string } {
    const name = user.dictionary?.users?.[user.sub]?.trim() || null;
    const roleTitle = ({ staff: '客服', leader: '客服主管', admin: '客服' } as Record<string, string>)[user.role] ?? '客服';
    return { name, roleTitle };
  }

  // ─────────────────────────────────────────────
  // 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 };
  }

  @Post(':id/recall-feedback')
  @RequirePermission(Permission.PLAN_VIEW_OWN)
  @ApiOperation({
    summary: '召回反馈(plan 级)— 对"这条召回准不准"打拇指 + 文字(down 弹窗收集)',
  })
  async submitRecallFeedback(
    @TenantScope() scope: TenantScopeContext,
    @Param('id') planId: string,
    @Body() body: unknown,
  ) {
    const { feedback, note } = SubmitRecallFeedbackRequestSchema.parse(body);
    // 反馈是对 plan 本身的判断 → 直接写 followup_plans(正交于执行,不进事实层)
    const res = await this.prisma.followupPlan.updateMany({
      where: { id: planId, hostId: scope.hostId, tenantId: scope.tenantId },
      data: {
        recallFeedback: feedback,
        recallFeedbackNote: note?.trim() ? note.trim() : null,
      },
    });
    if (res.count === 0) return { ok: false as const, reason: 'not_found' };
    return { ok: true as const, 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> {
    // 摘要档为单次调用,暂不透传 signal(controller 断连仍会停心跳/停写);如需取消在途再透传
    await this.pipeSse(res, () => this.planSummary.generateStream(planId, { modelIdOverride: model }));
  }

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

  private async pipeSse<T extends { type: string }>(
    res: Response,
    makeStream: (signal: AbortSignal) => 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?.();

    // ⭐ 客户端断连(关页面/点停止/网络断)→ abort:取消在途 LLM(尤其深度 3-4 步,别白烧)
    //    + 停心跳、停写,避免往已关闭 socket 写。
    const ac = new AbortController();
    res.on('close', () => ac.abort());

    // 心跳防代理断连(每 15s 一个注释行);socket 已关则不写
    const heartbeat = setInterval(() => {
      if (!res.writableEnded) res.write(': hb\n\n');
    }, 15_000);

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

/** 投入档 query 解析:只接受白名单,非法/缺省 → undefined(orchestrator 默认 stable) */
function parseScriptTier(tier: string | undefined): 'stable' | 'standard' | 'deep' | undefined {
  return tier === 'stable' || tier === 'standard' || tier === 'deep' ? tier : undefined;
}
