import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { Controller, Post, Get, Body, Req, Res, UseGuards } from '@nestjs/common';
import { AdminAiChatService } from './admin-ai-chat.service';
import { AiChatDto } from './dto/ai-chat.dto';
import { AdminAuthGuard } from '../../common/guards/admin-auth.guard';
import { AdminRolesGuard } from '../../common/guards/admin-roles.guard';
import { AdminRoles } from '../../common/decorators/admin-roles.decorator';
import type { AdminRole } from '../../common/types/admin-role.enum';
import type { Request, Response } from 'express';

@ApiTags('admin-ai-chat')
@Controller('admin-api/ai')
@UseGuards(AdminAuthGuard, AdminRolesGuard)
export class AdminAiChatController {
  constructor(private readonly aiChatService: AdminAiChatService) {}

  @Post('chat')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiBearerAuth()
  @ApiOperation({ summary: 'AI 对话（非流式，兼容旧版）' })
  async chat(@Body() dto: AiChatDto, @Req() req: Request & { adminUser: any }) {
    return this.aiChatService.chat(dto, req.adminUser.id);
  }

  @Post('chat/stream')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiBearerAuth()
  @ApiOperation({ summary: 'AI 对话（SSE 流式，支持 run 事件）' })
  async streamChat(@Body() dto: AiChatDto, @Req() req: Request & { adminUser: any }, @Res() res: Response) {
    return this.aiChatService.streamChat(dto, req.adminUser.id, res);
  }

  @Post('chat/stop')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiBearerAuth()
  @ApiOperation({ summary: '停止正在运行的 AI 任务' })
  async stopChat(@Body() body: { runId: string; action?: string }) {
        if (body.action) {
      // Approval: just forward to Hermes, don't kill the stream
      await fetch(`http://10.2.0.7:8642/v1/runs/${body.runId}/approval`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: 'Bearer zhixi-hermes-key-2026' },
        body: JSON.stringify({ choice: body.action }),
      }).catch(() => {});
      return { success: true };
    }
    // Stop: abort the stream
    return this.aiChatService.stopRun(body.runId);
  }

  @Get('dashboard')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取 Hermes Agent Dashboard 访问信息' })
  getDashboard() {
    return this.aiChatService.getDashboardConfig();
  }
}
