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

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

export const listPullRequestsTool = defineTool({
  description:
    "List recent pull requests in the repository with their state (open, closed, merged).",
  input: v.object({}),
  name: "list_pull_requests",
  async run() {
    const prs: GiteaPullRequest[] = await runWithGitea(
      Effect.gen(function* prs() {
        const gitea = yield* Gitea;
        return yield* gitea.listPullRequests();
      })
    );
    return {
      pullRequests: prs.map((pr) => ({
        base: pr.base,
        head: pr.head,
        merged: pr.merged,
        number: pr.number,
        state: pr.state,
        title: pr.title,
        url: pr.htmlUrl,
      })),
    };
  },
});

export const checkPrStatusTool = defineTool({
  description:
    "Check whether a specific pull request is open, merged, or closed. Use to verify if an issue's work was resolved.",
  input: v.object({
    number: v.pipe(v.number(), v.integer()),
  }),
  name: "check_pr_status",
  output: v.object({
    base: v.string(),
    head: v.string(),
    merged: v.boolean(),
    number: v.number(),
    state: v.string(),
    title: v.string(),
    url: v.string(),
  }),
  async run({ input }) {
    const pr: GiteaPullRequest = await runWithGitea(
      Effect.gen(function* pr() {
        const gitea = yield* Gitea;
        return yield* gitea.getPullRequest(input.number);
      })
    );
    return {
      base: pr.base,
      head: pr.head,
      merged: pr.merged,
      number: pr.number,
      state: pr.state,
      title: pr.title,
      url: pr.htmlUrl,
    };
  },
});
