/** Project tools — discover, register, and inspect the projects Forge manages.
 *  Management-only: metadata (roots, git, language, rules-presence, sessions),
 *  never project file contents. All in-process lib calls. */

import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { scanProjects, addProjectRoot, removeProjectRoot, SCRATCH_PROJECT_NAME } from '@/lib/projects';
import { text, fail, guard } from './_shared';

export function registerProjectTools(server: McpServer): void {
  server.tool(
    'forge_list_projects',
    'List the projects Forge can run tasks against (auto-discovered from the configured project roots). Each line shows name, language, whether it is a git repo, whether it has agent rules (CLAUDE.md), and last-modified date. Use a name with forge_create_task or forge_get_project. If none are registered, use forge_register_project.',
    {},
    () => guard(() => {
      const projects = scanProjects();
      const real = projects.filter((p) => p.name !== SCRATCH_PROJECT_NAME);
      if (real.length === 0) {
        return text('No projects registered yet (only the built-in "scratch" project exists). Register a folder that contains your projects with forge_register_project path="/path/to/code".');
      }
      const lines = projects.map((p) =>
        `• ${p.name}${p.language ? ` [${p.language}]` : ''}${p.hasGit ? ' (git)' : ''}${p.hasClaudeMd ? ' (rules)' : ''}`
        + ` — ${p.path}${p.lastModified ? ` · ${p.lastModified.slice(0, 10)}` : ''}`,
      );
      return text(`${projects.length} project(s):\n${lines.join('\n')}`);
    }),
  );

  server.tool(
    'forge_register_project',
    'Register a project root with Forge: a directory whose immediate subdirectories Forge will list as projects (e.g. "/Users/me/code", which contains your repos). Idempotent; validates the path exists. This is how you make new projects visible to forge_list_projects / forge_create_task.',
    { path: z.string().min(1).describe('Absolute path to a folder that CONTAINS your projects (not a single repo)') },
    (params) => guard(() => {
      const r = addProjectRoot(params.path);
      if (!r.ok) return fail(`Could not register "${params.path}": ${r.error}.`);
      if (r.alreadyRegistered) return text(`Already registered: ${r.root}.`);
      const added = scanProjects().filter((p) => p.root === r.root).map((p) => p.name);
      const found = added.length ? `\nProjects now visible from it: ${added.join(', ')}.` : '\n(No subdirectories found yet — add projects under it, then forge_list_projects.)';
      return text(`Registered project root ${r.root}.${found}`);
    }),
  );

  server.tool(
    'forge_unregister_project',
    'Unregister a project root (does NOT delete files — only stops Forge from listing its subdirectories as projects). Pass the root path exactly as shown in forge_get_project (root: …).',
    { path: z.string().min(1).describe('Absolute path of the root to unregister') },
    (params) => guard(() => {
      const r = removeProjectRoot(params.path);
      if (!r.ok) return fail(`Could not unregister "${params.path}": ${r.error}.`);
      return text(`Unregistered project root ${r.root}. Its subdirectories no longer appear in forge_list_projects.`);
    }),
  );

}
