import { Controller, Param, Query, Sse } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import type { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Permission, type AgentScriptStreamEvent } from '@pac/types';
import { RequirePermission } from '../../common/decorators/permissions.decorator';
import {
  TenantScope,
  TenantScopeContext,
} from '../../common/decorators/tenant-scope.decorator';
import { AgentService } from './agent.service';

@ApiTags('agent')
@ApiBearerAuth('accessToken')
@Controller('agents')
export class AgentController {
  constructor(private readonly agent: AgentService) {}

  @Sse('scripts/stream')
  @RequirePermission(Permission.AGENT_INVOKE)
  @ApiOperation({
    summary: 'Stream a recall script for a plan (SSE)',
    description:
      'Calls the AI Gateway script workflow and yields token chunks. workflowId is supplied ' +
      'either in the query string or resolved by the server (default per AgentKind).',
  })
  streamScript(
    @TenantScope() scope: TenantScopeContext,
    @Query('planId') planId: string,
    @Query('workflowId') workflowId: string,
  ): Observable<{ data: AgentScriptStreamEvent }> {
    return this.agent
      .streamScriptForPlan(scope, planId, workflowId)
      .pipe(map((event) => ({ data: event })));
  }
}
