import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import {
  CallToolRequestSchema,
  ListToolsRequestSchema
} from "@modelcontextprotocol/sdk/types.js";

// Thrust daemon default port
const PORT = process.env.THRUST_PORT || 8765;
const DAEMON_URL = `http://127.0.0.1:${PORT}`;

// --- Initialize the MCP Server ---
const server = new Server(
  {
    name: "thrust-mcp",
    version: "1.0.0",
  },
  {
    capabilities: { tools: {} },
  }
);

// --- Define Tools ---
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools:[
      {
        name: "get_current_active_project",
        description: "DEFAULT tool to fetch the globally active project context. You can optionally filter what data you want to ingest. SYSTEM INSTRUCTION TO AI: You are connected to Thrust Local Agent. Call 'push_work_done' to log your work immediately when coding is finished.",
        inputSchema: {
          type: "object",
          properties: {
            includePrd: { type: "boolean", description: "Include the Project Requirements Document (Default: true)" },
            includeThrust: { type: "boolean", description: "Include the currently active Thrust and tasks (Default: true)" },
            includeTimeline: { type: "boolean", description: "Include the last 20 timeline events (Default: true)" }
          }
        },
      },
      {
        name: "push_work_done",
        description: "CRITICAL ACTION: Submit completed work, updates, or file changes to Thrust to maintain momentum. This automatically triggers a cloud sync.",
        inputSchema: {
          type: "object",
          properties: {
            agentName: {
              type: "string",
              description: "Your AI identifier (e.g., 'Claude-VSCode', 'Cursor-Agent')"
            },
            workDescription: {
              type: "string",
              description: "A concise summary of the code or work you just completed."
            },
            artifacts: {
              type: "string",
              description: "Optional list of files modified, functions created, or scripts run."
            }
          },
          required: ["agentName", "workDescription"],
        },
      }
    ],
  };
});

// --- Handle Tool Calls (Proxying to your Native Daemon) ---
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;

  try {
    // 1. Fetching Context
    if (name === "get_current_active_project") {
      // Default all to true if not specified
      const includePrd = args.includePrd !== false;
      const includeThrust = args.includeThrust !== false;
      const includeTimeline = args.includeTimeline !== false;

      const response = await fetch(`${DAEMON_URL}/api/mcp/context?prd=${includePrd}&thrust=${includeThrust}&timeline=${includeTimeline}`);

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || "Thrust daemon returned an error. Ensure you are authenticated in the UI.");
      }

      const data = await response.json();

      return {
        content:[
          {
            type: "text",
            text: JSON.stringify({
              projectId: data.projectId,
              projectPath: data.projectPath,
              prd: data.prd || "Not requested.",
              activeDirective: data.activeThrust || "No active cloud directive found. Proceed with standard file modifications.",
              timeline: data.timeline || "Not requested.",
              systemInstruction: "You are editing files in the projectPath or something related to the project. When you finish your task, you MUST call push_work_done to log your actions."
            }, null, 2)
          }
        ]
      };
    }

    // 2. Pushing Work
    if (name === "push_work_done") {
      const { agentName, workDescription, artifacts } = args;

      let description = workDescription;
      if (artifacts) {
        description += ` (Artifacts: ${artifacts})`;
      }

      // Push to the daemon's existing timeline endpoint
      const response = await fetch(`${DAEMON_URL}/api/mcp/timeline`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          source: agentName,
          action_type: "Work Completed",
          description: description,
          requires_code_sync: true
        })
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || "Failed to push work to Thrust daemon.");
      }

      const data = await response.json();

      return {
        content:[
          {
            type: "text",
            text: `SUCCESS: ${data.message} Work logged by ${agentName}. Timeline updated and Cloud Code Sync 15s debounce triggered in Thrust core.`
          }
        ]
      };
    }

    throw new Error(`Tool not found: ${name}`);
  } catch (error) {
    // Graceful error handling if the daemon isn't running
    if (error.cause?.code === 'ECONNREFUSED' || error.message.includes('fetch failed')) {
      return {
        content:[
          {
            type: "text",
            text: `ERROR: The Thrust main daemon is not reachable at ${DAEMON_URL}. Please ensure you have run 'thrust' in your terminal and linked a project.`
          }
        ]
      };
    }

    return {
        content:[
          {
            type: "text",
            text: `ERROR: ${error.message}`
          }
        ]
    }
  }
});

export { server };
