// Copyright (C) 2026 Rob Colbert <rob.colbert@openplatform.us>
// Licensed under the Apache License, Version 2.0

import type { IAiLogger, IToolArguments } from "@gadget/ai";
import { DroneTool } from "../tool.ts";

export class ReadSkillTool extends DroneTool {
  get name(): string {
    return "read_skill";
  }

  get category(): string {
    return "project";
  }

  public definition = {
    type: "function" as const,
    function: {
      name: this.name,
      description:
        "Read the full content of a project skill by its index number. Use list_skills() first to see available skills and their indices.",
      parameters: {
        type: "object",
        properties: {
          index: {
            type: "number",
            description: "The skill index from list_skills()",
          },
        },
        required: ["index"],
      },
    },
  };

  public async execute(args: IToolArguments, _logger: IAiLogger): Promise<string> {
    const project = this.toolbox.env.project;
    if (!project) {
      return "No project is configured for this session.";
    }

    const index = typeof args.index === "number" ? args.index : parseInt(String(args.index), 10);
    if (isNaN(index)) {
      return "Invalid index. Provide a numeric index from list_skills().";
    }

    const mode = this.toolbox.env.chatSessionMode;
    const skills = project.skills.filter(
      (s) => mode && s.modes.includes(mode),
    );

    if (index < 0 || index >= skills.length) {
      return `Skill index ${index} not found. Use list_skills() to see available skills.`;
    }

    const skill = skills[index];
    const lines: string[] = [
      `Skill: ${skill.name} (${mode} mode)`,
      "",
      skill.content,
    ];

    return lines.join("\n");
  }
}
