#!/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 = "acuity-scheduling";
const MCP_VERSION = "1.0.0";
const API_BASE_URL = "https://acuityscheduling.com/api/v1";

// ============================================
// API CLIENT - Acuity uses Basic Auth
// ============================================
class AcuityClient {
  private authHeader: string;
  private baseUrl: string;

  constructor(userId: string, apiKey: string) {
    // Acuity uses Basic Auth with userId:apiKey
    this.authHeader = "Basic " + Buffer.from(`${userId}:${apiKey}`).toString("base64");
    this.baseUrl = API_BASE_URL;
  }

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

    if (!response.ok) {
      const text = await response.text();
      throw new Error(`Acuity 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" });
  }
}

// ============================================
// TOOL DEFINITIONS
// ============================================
const tools = [
  {
    name: "list_appointments",
    description: "List appointments with optional filters. Returns scheduled appointments.",
    inputSchema: {
      type: "object" as const,
      properties: {
        minDate: { type: "string", description: "Minimum date (YYYY-MM-DD)" },
        maxDate: { type: "string", description: "Maximum date (YYYY-MM-DD)" },
        calendarID: { type: "number", description: "Filter by calendar ID" },
        appointmentTypeID: { type: "number", description: "Filter by appointment type ID" },
        canceled: { type: "boolean", description: "Include canceled appointments" },
        max: { type: "number", description: "Maximum number of results (default 100)" },
      },
    },
  },
  {
    name: "get_appointment",
    description: "Get a specific appointment by ID",
    inputSchema: {
      type: "object" as const,
      properties: {
        id: { type: "number", description: "Appointment ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "create_appointment",
    description: "Create a new appointment",
    inputSchema: {
      type: "object" as const,
      properties: {
        datetime: { type: "string", description: "Appointment datetime (ISO 8601 format)" },
        appointmentTypeID: { type: "number", description: "Appointment type ID" },
        calendarID: { type: "number", description: "Calendar ID" },
        firstName: { type: "string", description: "Client first name" },
        lastName: { type: "string", description: "Client last name" },
        email: { type: "string", description: "Client email" },
        phone: { type: "string", description: "Client phone number" },
        notes: { type: "string", description: "Appointment notes" },
        fields: { type: "array", description: "Custom intake form fields", items: { type: "object" } },
      },
      required: ["datetime", "appointmentTypeID", "firstName", "lastName", "email"],
    },
  },
  {
    name: "cancel_appointment",
    description: "Cancel an appointment",
    inputSchema: {
      type: "object" as const,
      properties: {
        id: { type: "number", description: "Appointment ID to cancel" },
        cancelNote: { type: "string", description: "Reason for cancellation" },
        noShow: { type: "boolean", description: "Mark as no-show instead of cancel" },
      },
      required: ["id"],
    },
  },
  {
    name: "list_calendars",
    description: "List all calendars/staff members",
    inputSchema: {
      type: "object" as const,
      properties: {},
    },
  },
  {
    name: "get_availability",
    description: "Get available time slots for booking",
    inputSchema: {
      type: "object" as const,
      properties: {
        appointmentTypeID: { type: "number", description: "Appointment type ID" },
        calendarID: { type: "number", description: "Calendar ID (optional)" },
        date: { type: "string", description: "Date to check (YYYY-MM-DD)" },
        month: { type: "string", description: "Month to check (YYYY-MM)" },
        timezone: { type: "string", description: "Timezone (e.g., America/New_York)" },
      },
      required: ["appointmentTypeID"],
    },
  },
  {
    name: "list_clients",
    description: "List clients with optional search",
    inputSchema: {
      type: "object" as const,
      properties: {
        search: { type: "string", description: "Search term (name, email, or phone)" },
        max: { type: "number", description: "Maximum number of results" },
      },
    },
  },
];

// ============================================
// TOOL HANDLERS
// ============================================
async function handleTool(client: AcuityClient, name: string, args: any) {
  switch (name) {
    case "list_appointments": {
      const params = new URLSearchParams();
      if (args.minDate) params.append("minDate", args.minDate);
      if (args.maxDate) params.append("maxDate", args.maxDate);
      if (args.calendarID) params.append("calendarID", String(args.calendarID));
      if (args.appointmentTypeID) params.append("appointmentTypeID", String(args.appointmentTypeID));
      if (args.canceled !== undefined) params.append("canceled", String(args.canceled));
      if (args.max) params.append("max", String(args.max));
      const query = params.toString();
      return await client.get(`/appointments${query ? `?${query}` : ""}`);
    }

    case "get_appointment": {
      return await client.get(`/appointments/${args.id}`);
    }

    case "create_appointment": {
      const payload: any = {
        datetime: args.datetime,
        appointmentTypeID: args.appointmentTypeID,
        firstName: args.firstName,
        lastName: args.lastName,
        email: args.email,
      };
      if (args.calendarID) payload.calendarID = args.calendarID;
      if (args.phone) payload.phone = args.phone;
      if (args.notes) payload.notes = args.notes;
      if (args.fields) payload.fields = args.fields;
      return await client.post("/appointments", payload);
    }

    case "cancel_appointment": {
      const payload: any = {};
      if (args.cancelNote) payload.cancelNote = args.cancelNote;
      if (args.noShow) payload.noShow = args.noShow;
      return await client.put(`/appointments/${args.id}/cancel`, payload);
    }

    case "list_calendars": {
      return await client.get("/calendars");
    }

    case "get_availability": {
      const params = new URLSearchParams();
      params.append("appointmentTypeID", String(args.appointmentTypeID));
      if (args.calendarID) params.append("calendarID", String(args.calendarID));
      if (args.date) params.append("date", args.date);
      if (args.month) params.append("month", args.month);
      if (args.timezone) params.append("timezone", args.timezone);
      return await client.get(`/availability/times?${params.toString()}`);
    }

    case "list_clients": {
      const params = new URLSearchParams();
      if (args.search) params.append("search", args.search);
      if (args.max) params.append("max", String(args.max));
      const query = params.toString();
      return await client.get(`/clients${query ? `?${query}` : ""}`);
    }

    default:
      throw new Error(`Unknown tool: ${name}`);
  }
}

// ============================================
// SERVER SETUP
// ============================================
async function main() {
  const userId = process.env.ACUITY_USER_ID;
  const apiKey = process.env.ACUITY_API_KEY;
  
  if (!userId || !apiKey) {
    console.error("Error: ACUITY_USER_ID and ACUITY_API_KEY environment variables required");
    process.exit(1);
  }

  const client = new AcuityClient(userId, apiKey);

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

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

  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,
      };
    }
  });

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

main().catch(console.error);
