#!/usr/bin/env node
/**
 * GoodGo MCP Server — AI-assisted F&B operations
 *
 * Exposes tools for catalog, inventory, recipe, and analytics management
 * through the Model Context Protocol (MCP).
 *
 * Transport: stdio (for Claude Code local integration)
 *
 * Usage:
 *   claude mcp add --transport stdio goodgo -- node dist/index.js
 */
import dotenv from "dotenv";
dotenv.config();

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

import { registerCatalogTools } from "./tools/catalog-tools.js";
import { registerInventoryTools } from "./tools/inventory-tools.js";
import { registerRecipeTools } from "./tools/recipe-tools.js";
import { registerAnalyticsTools } from "./tools/analytics-tools.js";

// Startup validation
if (!process.env.API_TOKEN) {
  console.error(
    "WARNING: API_TOKEN is not set. All API calls will fail with 401.\n" +
    "Get a token: curl -s http://localhost/connect/token -d 'grant_type=password&username=...&password=...&client_id=password-client&client_secret=password-client-secret'\n" +
    "Then add it to services/goodgo-mcp-server/.env"
  );
}

const server = new McpServer({
  name: "goodgo",
  version: "1.0.0",
  description: `GoodGo MCP Server — AI assistant for F&B shop operations.

Available tool groups:
- Catalog: list/create/update/delete products and menu items
- Inventory: check stock, record intake (nhap kho), record usage (xuat kho), low stock alerts
- Recipes: list and create recipes with ingredients
- Analytics: popular items, cost analysis

Default shop: Cobic Coffee (${process.env.DEFAULT_SHOP_ID || "e1f392af-fe95-4c7f-8656-5b74ad5fd0a9"})
If user doesn't specify shopId, use the default.

All prices are in VND (Vietnamese Dong). Format as X.000d (e.g., 45.000d).
`,
});

// Register all tool groups
registerCatalogTools(server);
registerInventoryTools(server);
registerRecipeTools(server);
registerAnalyticsTools(server);

// Graceful shutdown
async function shutdown() {
  try {
    await server.close();
  } catch {
    // ignore close errors
  }
  process.exit(0);
}

process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);

// Start server
try {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("GoodGo MCP Server started (stdio transport)");
} catch (err) {
  console.error("Failed to start MCP server:", err instanceof Error ? err.message : err);
  process.exit(1);
}
