import { Injectable } from '@nestjs/common';
import { BrowserExecutorService } from './browser-executor.service';
import { AgentExecutorService } from './agent-executor.service';
import { RoutedExecutionResult } from './executor.types';
import { InspectionTaskEntity } from '../tasks/inspection-task.entity';

@Injectable()
export class ExecutionRouterService {
  constructor(
    private readonly browserExecutorService: BrowserExecutorService,
    private readonly agentExecutorService: AgentExecutorService,
  ) {}

  async executeTask(
    task: Pick<
      InspectionTaskEntity,
      | 'id'
      | 'name'
      | 'siteUrl'
      | 'stepsJson'
      | 'preferredExecutor'
      | 'allowAgentFallback'
    >,
    traceId: string,
  ): Promise<RoutedExecutionResult> {
    if (task.preferredExecutor === 'agent-s') {
      const result = await this.agentExecutorService.executeTask(task, traceId);
      return {
        ...result,
        routePolicy: 'agent-only',
      };
    }

    const browserResult = await this.browserExecutorService.executeTask(
      task,
      traceId,
    );

    if (
      task.allowAgentFallback &&
      (browserResult.status === 'failed' || browserResult.status === 'partial')
    ) {
      const agentResult = await this.agentExecutorService.executeTask(
        task,
        traceId,
      );

      if (agentResult.status === 'success') {
        return {
          ...agentResult,
          routePolicy: 'browser-first',
        };
      }
    }

    return {
      ...browserResult,
      routePolicy: task.allowAgentFallback ? 'browser-first' : 'browser-only',
    };
  }
}
