#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
  McpError,
  ErrorCode,
} from "@modelcontextprotocol/sdk/types.js";

// ============================================
// CONFIGURATION
// ============================================
const MCP_NAME = "wrike";
const MCP_VERSION = "1.0.0";
const API_BASE_URL = "https://www.wrike.com/api/v4";

// ============================================
// API CLIENT
// ============================================
class WrikeClient {
  private accessToken: string;
  private baseUrl: string;

  constructor(accessToken: string) {
    this.accessToken = accessToken;
    this.baseUrl = API_BASE_URL;
  }

  async request(endpoint: string, options: RequestInit = {}) {
    const url = `${this.baseUrl}${endpoint}`;
    const response = await fetch(url, {
      ...options,
      headers: {
        "Authorization": `Bearer ${this.accessToken}`,
        "Content-Type": "application/json",
        ...options.headers,
      },
    });

    if (!response.ok) {
      const text = await response.text();
      throw new Error(`Wrike API error: ${response.status} ${response.statusText} - ${text}`);
    }

    return response.json();
  }

  async get(endpoint: string) {
    return this.request(endpoint, { method: "GET" });
  }

  async post(endpoint: string, data: any) {
    return this.request(endpoint, {
      method: "POST",
      body: JSON.stringify(data),
    });
  }

  async put(endpoint: string, data: any) {
    return this.request(endpoint, {
      method: "PUT",
      body: JSON.stringify(data),
    });
  }

  async delete(endpoint: string) {
    return this.request(endpoint, { method: "DELETE" });
  }

  // Task methods
  async listTasks(folderId?: string, options?: { status?: string; limit?: number }) {
    let endpoint = folderId ? `/folders/${folderId}/tasks` : "/tasks";
    const params = new URLSearchParams();
    if (options?.status) params.append("status", options.status);
    if (options?.limit) params.append("pageSize", options.limit.toString());
    if (params.toString()) endpoint += `?${params.toString()}`;
    return this.get(endpoint);
  }

  async getTask(taskId: string) {
    return this.get(`/tasks/${taskId}`);
  }

  async createTask(folderId: string, data: {
    title: string;
    description?: string;
    status?: string;
    importance?: string;
    dates?: { start?: string; due?: string };
    responsibles?: string[];
  }) {
    return this.post(`/folders/${folderId}/tasks`, data);
  }

  async updateTask(taskId: string, data: {
    title?: string;
    description?: string;
    status?: string;
    importance?: string;
    dates?: { start?: string; due?: string };
    addResponsibles?: string[];
    removeResponsibles?: string[];
  }) {
    return this.put(`/tasks/${taskId}`, data);
  }

  // Folder methods
  async listFolders(parentFolderId?: string) {
    const endpoint = parentFolderId ? `/folders/${parentFolderId}/folders` : "/folders";
    return this.get(endpoint);
  }

  // Project methods (projects are folders with project=true)
  async listProjects() {
    return this.get("/folders?project=true");
  }

  // Comment methods
  async addComment(taskId: string, text: string) {
    return this.post(`/tasks/${taskId}/comments`, { text });
  }

  // User/Contact methods
  async listUsers() {
    return this.get("/contacts");
  }
}

// ============================================
// TOOL DEFINITIONS
// ============================================
const tools = [
  {
    name: "list_tasks",
    description: "List tasks from Wrike. Can filter by folder and status.",
    inputSchema: {
      type: "object" as const,
      properties: {
        folder_id: { type: "string", description: "Optional folder ID to filter tasks" },
        status: { 
          type: "string", 
          description: "Filter by status: Active, Completed, Deferred, Cancelled",
          enum: ["Active", "Completed", "Deferred", "Cancelled"]
        },
        limit: { type: "number", description: "Max tasks to return (default 100)" },
      },
    },
  },
  {
    name: "get_task",
    description: "Get a specific task by ID from Wrike",
    inputSchema: {
      type: "object" as const,
      properties: {
        task_id: { type: "string", description: "The task ID" },
      },
      required: ["task_id"],
    },
  },
  {
    name: "create_task",
    description: "Create a new task in Wrike",
    inputSchema: {
      type: "object" as const,
      properties: {
        folder_id: { type: "string", description: "Folder ID to create task in" },
        title: { type: "string", description: "Task title" },
        description: { type: "string", description: "Task description" },
        status: { 
          type: "string", 
          description: "Task status",
          enum: ["Active", "Completed", "Deferred", "Cancelled"]
        },
        importance: { 
          type: "string", 
          description: "Task importance",
          enum: ["High", "Normal", "Low"]
        },
        start_date: { type: "string", description: "Start date (YYYY-MM-DD)" },
        due_date: { type: "string", description: "Due date (YYYY-MM-DD)" },
        responsibles: { 
          type: "array", 
          items: { type: "string" },
          description: "Array of user IDs to assign"
        },
      },
      required: ["folder_id", "title"],
    },
  },
  {
    name: "update_task",
    description: "Update an existing task in Wrike",
    inputSchema: {
      type: "object" as const,
      properties: {
        task_id: { type: "string", description: "Task ID to update" },
        title: { type: "string", description: "New task title" },
        description: { type: "string", description: "New task description" },
        status: { 
          type: "string", 
          description: "Task status",
          enum: ["Active", "Completed", "Deferred", "Cancelled"]
        },
        importance: { 
          type: "string", 
          description: "Task importance",
          enum: ["High", "Normal", "Low"]
        },
        start_date: { type: "string", description: "Start date (YYYY-MM-DD)" },
        due_date: { type: "string", description: "Due date (YYYY-MM-DD)" },
        add_responsibles: { 
          type: "array", 
          items: { type: "string" },
          description: "User IDs to add as assignees"
        },
        remove_responsibles: { 
          type: "array", 
          items: { type: "string" },
          description: "User IDs to remove from assignees"
        },
      },
      required: ["task_id"],
    },
  },
  {
    name: "list_folders",
    description: "List folders from Wrike. Can get child folders of a parent.",
    inputSchema: {
      type: "object" as const,
      properties: {
        parent_folder_id: { type: "string", description: "Optional parent folder ID" },
      },
    },
  },
  {
    name: "list_projects",
    description: "List all projects from Wrike",
    inputSchema: {
      type: "object" as const,
      properties: {},
    },
  },
  {
    name: "add_comment",
    description: "Add a comment to a task in Wrike",
    inputSchema: {
      type: "object" as const,
      properties: {
        task_id: { type: "string", description: "Task ID to comment on" },
        text: { type: "string", description: "Comment text (supports markdown)" },
      },
      required: ["task_id", "text"],
    },
  },
  {
    name: "list_users",
    description: "List all users/contacts in Wrike workspace",
    inputSchema: {
      type: "object" as const,
      properties: {},
    },
  },
];

// ============================================
// TOOL HANDLERS
// ============================================
async function handleTool(client: WrikeClient, name: string, args: any) {
  switch (name) {
    case "list_tasks": {
      return await client.listTasks(args.folder_id, {
        status: args.status,
        limit: args.limit,
      });
    }
    case "get_task": {
      return await client.getTask(args.task_id);
    }
    case "create_task": {
      const dates: { start?: string; due?: string } = {};
      if (args.start_date) dates.start = args.start_date;
      if (args.due_date) dates.due = args.due_date;
      
      return await client.createTask(args.folder_id, {
        title: args.title,
        description: args.description,
        status: args.status,
        importance: args.importance,
        dates: Object.keys(dates).length ? dates : undefined,
        responsibles: args.responsibles,
      });
    }
    case "update_task": {
      const dates: { start?: string; due?: string } = {};
      if (args.start_date) dates.start = args.start_date;
      if (args.due_date) dates.due = args.due_date;
      
      return await client.updateTask(args.task_id, {
        title: args.title,
        description: args.description,
        status: args.status,
        importance: args.importance,
        dates: Object.keys(dates).length ? dates : undefined,
        addResponsibles: args.add_responsibles,
        removeResponsibles: args.remove_responsibles,
      });
    }
    case "list_folders": {
      return await client.listFolders(args.parent_folder_id);
    }
    case "list_projects": {
      return await client.listProjects();
    }
    case "add_comment": {
      return await client.addComment(args.task_id, args.text);
    }
    case "list_users": {
      return await client.listUsers();
    }
    default:
      throw new Error(`Unknown tool: ${name}`);
  }
}

// ============================================
// SERVER SETUP
// ============================================
async function main() {
  const accessToken = process.env.WRIKE_ACCESS_TOKEN;
  if (!accessToken) {
    console.error("Error: WRIKE_ACCESS_TOKEN environment variable required");
    process.exit(1);
  }

  const client = new WrikeClient(accessToken);

  const server = new Server(
    { name: `${MCP_NAME}-mcp`, version: MCP_VERSION },
    { capabilities: { tools: {} } }
  );

  // List available tools
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
    tools,
  }));

  // Handle tool calls
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
    const { name, arguments: args } = request.params;

    // Validate tool exists (MCP spec requires proper error for unknown tools)
    const knownTools = tools.map(t => t.name);
    if (!knownTools.includes(name)) {
      throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
    }
    
    try {
      const result = await handleTool(client, name, args || {});
      return {
        content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
      };
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      return {
        content: [{ type: "text", text: `Error: ${message}` }],
        isError: true,
      };
    }
  });

  // Start server
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error(`${MCP_NAME} MCP server running on stdio`);
}

main().catch(console.error);
