#!/usr/bin/env node

/**
 * Crow — Terminal Setup Wizard (fallback)
 *
 * Text-based wizard for headless environments. Uses Node.js readline.
 * The web wizard (wizard-web.js) is preferred for most users.
 *
 * Usage: node scripts/wizard.js --terminal
 */

import { createInterface } from "readline";
import { readFileSync, writeFileSync, existsSync } from "fs";
import { resolve, dirname } from "path";
import { fileURLToPath } from "url";
import { execSync } from "child_process";

const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const ENV_PATH = resolve(ROOT, ".env");

const rl = createInterface({ input: process.stdin, output: process.stdout });
const ask = (q) => new Promise((res) => rl.question(q, res));

const INTEGRATIONS = [
  {
    key: "trello", name: "Trello", desc: "Project boards and cards",
    envVars: [
      { key: "TRELLO_API_KEY", prompt: "Trello API Key", url: "https://trello.com/power-ups/admin" },
      { key: "TRELLO_TOKEN", prompt: "Trello Token", url: "https://trello.com/1/authorize?expiration=never&scope=read,write&response_type=token&key=YOUR_API_KEY" }
    ]
  },
  {
    key: "canvas", name: "Canvas LMS", desc: "Courses, assignments, and grades",
    envVars: [
      { key: "CANVAS_API_TOKEN", prompt: "Canvas API Token", url: "Canvas > Account > Settings > New Access Token" },
      { key: "CANVAS_BASE_URL", prompt: "Canvas Base URL (e.g., https://school.instructure.com)", url: null }
    ]
  },
  {
    key: "google", name: "Google Workspace", desc: "Gmail, Calendar, Docs, Sheets, Slides, Chat",
    envVars: [
      { key: "GOOGLE_CLIENT_ID", prompt: "Google OAuth Client ID (optional — auto sign-in works without)", url: "https://console.cloud.google.com/apis/credentials" },
      { key: "GOOGLE_CLIENT_SECRET", prompt: "Google OAuth Client Secret (optional)", url: null }
    ]
  },
  {
    key: "notion", name: "Notion", desc: "Wiki pages, databases, knowledge base",
    envVars: [{ key: "NOTION_TOKEN", prompt: "Notion Integration Token", url: "https://www.notion.so/my-integrations" }]
  },
  {
    key: "slack", name: "Slack", desc: "Team messaging and channels",
    envVars: [{ key: "SLACK_BOT_TOKEN", prompt: "Slack Bot Token (xoxb-...)", url: "https://api.slack.com/apps" }]
  },
  {
    key: "discord", name: "Discord", desc: "Community servers and channels",
    envVars: [{ key: "DISCORD_BOT_TOKEN", prompt: "Discord Bot Token", url: "https://discord.com/developers/applications" }]
  },
  {
    key: "teams", name: "Microsoft Teams (experimental)", desc: "Teams chats and channels",
    envVars: [
      { key: "TEAMS_CLIENT_ID", prompt: "Azure AD App Client ID", url: "https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps" },
      { key: "TEAMS_CLIENT_SECRET", prompt: "Azure AD App Client Secret", url: null },
      { key: "TEAMS_TENANT_ID", prompt: "Azure AD Tenant ID", url: null }
    ]
  },
  {
    key: "github", name: "GitHub", desc: "Repos, issues, pull requests",
    envVars: [{ key: "GITHUB_PERSONAL_ACCESS_TOKEN", prompt: "GitHub Personal Access Token", url: "https://github.com/settings/tokens" }]
  },
  {
    key: "brave", name: "Brave Search", desc: "Web search for research",
    envVars: [{ key: "BRAVE_API_KEY", prompt: "Brave Search API Key", url: "https://brave.com/search/api/" }]
  },
  {
    key: "zotero", name: "Zotero", desc: "Citation and reference management",
    envVars: [
      { key: "ZOTERO_API_KEY", prompt: "Zotero API Key", url: "https://www.zotero.org/settings/keys" },
      { key: "ZOTERO_USER_ID", prompt: "Zotero User ID", url: null }
    ]
  }
];

function loadExistingEnv() {
  const env = {};
  if (existsSync(ENV_PATH)) {
    for (const line of readFileSync(ENV_PATH, "utf8").split("\n")) {
      const t = line.trim();
      if (!t || t.startsWith("#")) continue;
      const eq = t.indexOf("=");
      if (eq === -1) continue;
      const val = t.slice(eq + 1).trim();
      if (val) env[t.slice(0, eq).trim()] = val;
    }
  }
  return env;
}

function saveEnv(env) {
  const lines = [
    "# Crow - Environment Variables",
    "# Generated by setup wizard",
    "",
    `CROW_DB_PATH=${env.CROW_DB_PATH || "./data/crow.db"}`,
    `CROW_FILES_PATH=${env.CROW_FILES_PATH || "/home"}`,
    ""
  ];
  for (const integration of INTEGRATIONS) {
    const hasAny = integration.envVars.some((v) => env[v.key]);
    if (hasAny) {
      lines.push(`# === ${integration.name} ===`);
      for (const v of integration.envVars) {
        lines.push(`${v.key}=${env[v.key] || ""}`);
      }
      lines.push("");
    }
  }
  writeFileSync(ENV_PATH, lines.join("\n"));
}

async function main() {
  console.log("\n" + "=".repeat(55));
  console.log("   Crow — Setup Wizard (Terminal Mode)");
  console.log("=".repeat(55));
  console.log("\n  Tip: Run without --terminal for the web-based wizard.\n");
  console.log("  This wizard will help you configure your integrations.");
  console.log("  You can skip any integration you don't need.\n");

  const env = loadExistingEnv();
  const enabled = [];

  console.log("  Always enabled (no setup needed):");
  console.log("    - Crow Memory, Research Pipeline, Academic Search, Filesystem\n");

  for (const integration of INTEGRATIONS) {
    const existing = integration.envVars.every((v) => env[v.key]);
    const status = existing ? " [already configured]" : "";

    const answer = await ask(`  Enable ${integration.name}? (${integration.desc})${status} [y/N] `);
    if (answer.toLowerCase() !== "y" && answer.toLowerCase() !== "yes") continue;

    enabled.push(integration.name);
    console.log("");

    for (const v of integration.envVars) {
      if (env[v.key]) {
        const masked = env[v.key].slice(0, 4) + "..." + env[v.key].slice(-4);
        const keep = await ask(`    ${v.prompt} (current: ${masked}) — keep? [Y/n] `);
        if (keep.toLowerCase() !== "n" && keep.toLowerCase() !== "no") continue;
      }
      if (v.url) console.log(`    Get yours at: ${v.url}`);
      const value = await ask(`    ${v.prompt}: `);
      if (value.trim()) env[v.key] = value.trim();
    }
    console.log("");
  }

  saveEnv(env);
  console.log("  Saved configuration to .env\n");

  // Always regenerate .mcp.json
  try {
    execSync("node scripts/generate-mcp-config.js", { cwd: ROOT, stdio: "inherit" });
  } catch {
    console.log("  Warning: Could not generate .mcp.json.");
  }

  const genDesktop = await ask("  Generate Claude Desktop config? [Y/n] ");
  if (genDesktop.toLowerCase() !== "n" && genDesktop.toLowerCase() !== "no") {
    try {
      execSync("node scripts/generate-desktop-config.js", { cwd: ROOT, stdio: "inherit" });
    } catch {
      console.log("  Warning: Could not generate desktop config.");
    }
  }

  console.log("\n" + "=".repeat(55));
  console.log("   Setup Complete!");
  console.log("=".repeat(55));
  if (enabled.length > 0) {
    console.log(`\n  Enabled: ${enabled.join(", ")}`);
  }
  console.log("\n  Next: Run 'claude' in this directory or restart Claude Desktop.\n");
  rl.close();
}

main().catch((err) => {
  console.error("Setup wizard error:", err);
  rl.close();
  process.exit(1);
});
