import { Injectable } from '@nestjs/common';
import { ToolExecutionResult, ToolContext, ToolDefinition } from './tool.types';
import { LokiClient } from '../../outbound/loki/loki.client';

type LokiQueryRangeArgs = {
  query: string;
  start?: string;
  end?: string;
  step?: string;
  limit?: number;
};

@Injectable()
export class LokiQueryRangeUsecase {
  constructor(private readonly lokiClient: LokiClient) {}

  definition(): ToolDefinition {
    return {
      name: 'loki.query_range',
      description: 'Run a LogQL range query against Loki.',
      inputSchema: {
        type: 'object',
        properties: {
          query: { type: 'string', description: 'LogQL query' },
          start: { type: 'string', description: 'RFC3339 or epoch' },
          end: { type: 'string', description: 'RFC3339 or epoch' },
          step: { type: 'string', description: 'e.g. 10s, 1m' },
          limit: { type: 'integer', minimum: 1, maximum: 5000 },
        },
        required: ['query'],
        additionalProperties: false,
      },
      handler: async (args, context) => this.execute(args, context),
    };
  }

  async execute(args: unknown, _context: ToolContext): Promise<ToolExecutionResult> {
    const typedArgs = (args ?? {}) as LokiQueryRangeArgs;

    try {
      const payload = await this.lokiClient.queryRange({
        query: typedArgs.query,
        start: typedArgs.start,
        end: typedArgs.end,
        step: typedArgs.step,
        limit: typedArgs.limit,
      });

      return {
        output: [
          {
            kind: 'text',
            text: JSON.stringify(payload, null, 2),
          },
        ],
        isError: false,
      };
    } catch (error) {
      const details = error instanceof Error ? error.message : String(error);
      return {
        output: [{ kind: 'text', text: `loki.query_range failed: ${details}` }],
        isError: true,
      };
    }
  }
}
