#!/usr/bin/env node

import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = dirname(fileURLToPath(import.meta.url));

function install() {
  const mcpConfig = {
    mcpServers: {
      tuitui: {
        command: "node",
        args: [resolve(__dirname, "server/boot.mjs")],
        env: {
          TUITUI_APP_ID: process.env.TUITUI_APP_ID || "",
          TUITUI_APP_SECRET: process.env.TUITUI_APP_SECRET || "",
          TUITUI_STATE_DIR:
            process.env.TUITUI_STATE_DIR || resolve(__dirname, ".state"),
          TUITUI_DM_POLICY: process.env.TUITUI_DM_POLICY || "allowlist",
          TUITUI_GROUP_POLICY: process.env.TUITUI_GROUP_POLICY || "allowlist",
          TUITUI_REQUIRE_MENTION: process.env.TUITUI_REQUIRE_MENTION || "true",
          TUITUI_CHANNEL_CONTEXT:
            process.env.TUITUI_CHANNEL_CONTEXT || "thread",
          TUITUI_AUTO_REPLY: process.env.TUITUI_AUTO_REPLY || "true",
        },
      },
    },
  };
  const mcpPath = resolve(process.cwd(), ".mcp.json");
  if (existsSync(mcpPath)) {
    try {
      const existing = JSON.parse(readFileSync(mcpPath, "utf8"));
      existing.mcpServers ||= {};
      existing.mcpServers.tuitui = mcpConfig.mcpServers.tuitui;
      writeFileSync(mcpPath, JSON.stringify(existing, null, 2) + "\n", "utf8");
      console.log(`Updated: ${mcpPath}`);
    } catch {
      writeFileSync(mcpPath, JSON.stringify(mcpConfig, null, 2) + "\n", "utf8");
      console.log(`Created: ${mcpPath}`);
    }
  } else {
    writeFileSync(mcpPath, JSON.stringify(mcpConfig, null, 2) + "\n", "utf8");
    console.log(`Created: ${mcpPath}`);
  }
  console.log("\nNext steps:");
  console.log("  1. Fill TUITUI_APP_ID / TUITUI_APP_SECRET in .mcp.json");
  console.log("  2. Start Claude Code with the local MCP config");
}

function help() {
  console.log(`
Claude TuiTui Channel

Usage: node cli.mjs <command>

Commands:
  start     Start the TuiTui MCP/channel server
  install   Write or update .mcp.json in current directory
  help      Show this help message
`);
}

const command = process.argv[2];
switch (command) {
  case "start":
    await import("./server/index.mjs");
    break;
  case "install":
    install();
    break;
  case "help":
  case "--help":
  case "-h":
  default:
    help();
    if (command && !["help", "--help", "-h"].includes(command)) process.exit(1);
}
