// SF2 — Read-only query tools exposing DB state to the LLM via the WAL connection

import { Type } from "@sinclair/typebox";
import type { ExtensionAPI } from "@singularity-forge/pi-coding-agent";
import { ensureDbOpen } from "./dynamic-tools.js";
import { executeMilestoneStatus } from "../tools/workflow-tool-executors.js";

export function registerQueryTools(pi: ExtensionAPI): void {
  pi.registerTool({
    name: "sf_milestone_status",
    label: "Milestone Status",
    description:
      "Read the current status of a milestone and all its slices from the SF database. " +
      "Returns milestone metadata, per-slice status, and task counts per slice. " +
      "Use this instead of querying .sf/sf.db directly via sqlite3 or better-sqlite3.",
    promptSnippet: "Get milestone status, slice statuses, and task counts for a given milestoneId",
    promptGuidelines: [
      "Use this tool — not sqlite3 or better-sqlite3 — to inspect milestone or slice state from the DB.",
    ],
    parameters: Type.Object({
      milestoneId: Type.String({ description: "Milestone ID to query (e.g. M001)" }),
    }),
    async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
      const dbAvailable = await ensureDbOpen();
      if (!dbAvailable) {
        return {
          content: [{ type: "text", text: "Error: SF database is not available. Cannot read milestone status." }],
          details: { operation: "milestone_status", error: "db_unavailable" },
        };
      }
      return executeMilestoneStatus(params);
    },
  });
}
