import { cmd } from "./cmd"
import * as prompts from "@clack/prompts"
import { UI } from "../ui"
import { Instance } from "../../project/instance"
import { configuredServers, listState } from "./mcp-shared"
import { MCP } from "../../mcp"
import { AppRuntime } from "../../effect/app-runtime"
import { Effect } from "effect"

export const McpRefreshCommand = cmd({
  command: "refresh",
  aliases: ["rf"],
  describe: "refresh MCP server list from config",
  async handler() {
    await Instance.provide({
      directory: process.cwd(),
      async fn() {
        UI.empty()
        prompts.intro("Refresh MCP Servers")

        const spinner = prompts.spinner()
        spinner.start("Reconnecting...")

        const statuses = await AppRuntime.runPromise(
          Effect.gen(function* () {
            const mcp = yield* MCP.Service
            return yield* mcp.refresh()
          }),
        )

        spinner.stop("Done")

        const { config } = await listState()
        const servers = configuredServers(config)

        for (const [name] of servers) {
          const s = statuses[name]
          if (!s) continue
          const icon = s.status === "connected" ? "✓" : s.status === "disabled" ? "○" : "✗"
          prompts.log.info(`${icon} ${name} ${UI.Style.TEXT_DIM}${s.status}`)
        }

        prompts.outro(`${servers.length} server(s) refreshed`)
      },
    })
  },
})
