import { defineTool } from "@flue/runtime";
import { Effect } from "effect";
import * as v from "valibot";

import { Gitea } from "../git/gitea-service";
import { runWithGitea } from "./runtime";

export const createIssueTool = defineTool({
  description:
    "Create a new issue in the repository. Use when the user describes actionable work that should be tracked.",
  input: v.object({
    body: v.pipe(v.string(), v.maxLength(20_000)),
    title: v.pipe(v.string(), v.minLength(1), v.maxLength(200)),
  }),
  name: "create_issue",
  output: v.object({
    htmlUrl: v.string(),
    number: v.number(),
    state: v.string(),
    title: v.string(),
  }),
  async run({ input }) {
    const issue = await runWithGitea(
      Effect.gen(function* issue() {
        const gitea = yield* Gitea;
        return yield* gitea.createIssue(input);
      })
    );
    return {
      htmlUrl: issue.htmlUrl,
      number: issue.number,
      state: issue.state,
      title: issue.title,
    };
  },
});

export const editIssueTool = defineTool({
  description:
    "Edit an existing issue's title, body, or state. Set state to 'closed' to resolve it.",
  input: v.object({
    body: v.optional(v.pipe(v.string(), v.maxLength(20_000))),
    number: v.pipe(v.number(), v.integer()),
    state: v.optional(v.picklist(["open", "closed"])),
    title: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(200))),
  }),
  name: "edit_issue",
  output: v.object({
    htmlUrl: v.string(),
    number: v.number(),
    state: v.string(),
    title: v.string(),
  }),
  async run({ input }) {
    const issue = await runWithGitea(
      Effect.gen(function* issue() {
        const gitea = yield* Gitea;
        return yield* gitea.editIssue(input.number, input);
      })
    );
    return {
      htmlUrl: issue.htmlUrl,
      number: issue.number,
      state: issue.state,
      title: issue.title,
    };
  },
});
