#!/usr/bin/env node
/**
 * tc — Treehouse CLI
 * Thin wrapper around @treehouse/sdk for use in agent containers and tenant workspaces.
 */

const SDK_PATH = '/opt/treehouse/sdk/dist/index.js';

const argv = process.argv.slice(2);

async function main() {
  const sdk = await import(SDK_PATH).catch(() => {
    console.error('Error: @treehouse/sdk not found at', SDK_PATH);
    process.exit(1);
  });

  const [command, sub, ...rest] = argv;

  switch (command) {

    // ── credentials ────────────────────────────────────────────
    case 'credentials':
    case 'creds': {
      const [csub, name, ...credRest] = [sub, ...rest];
      if (csub === 'get' && name) {
        const cred = await sdk.getCredential(name);
        console.log(cred.value);
      } else if (csub === 'set' && name) {
        let value, description;
        const setArgs = [...credRest];
        while (setArgs.length) {
          const a = setArgs.shift();
          if (a === '--description') description = setArgs.shift();
          else if (!value) value = a;
        }
        if (!value) { console.error('Usage: tc creds set <name> <value> [--description <desc>]'); process.exit(1); }
        await sdk.setCredential(name, value, description ? { description } : undefined);
        console.log('Credential set.');
      } else if (csub === 'remove' && name) {
        await sdk.removeCredential(name);
        console.log('Credential removed.');
      } else if (!csub || csub === 'list') {
        const creds = await sdk.listCredentials();
        if (creds.length === 0) { console.log('No credentials stored.'); break; }
        creds.forEach(c => console.log(`${c.name}${c.description ? `  # ${c.description}` : ''}`));
      } else {
        console.error('Usage: tc creds [list]\n       tc creds get <name>\n       tc creds set <name> <value> [--description <desc>]\n       tc creds remove <name>');
        process.exit(1);
      }
      break;
    }

    // ── tasks ──────────────────────────────────────────────────
    case 'tasks': {
      if (!sub || sub === 'list') {
        const tasks = await sdk.listTasks();
        if (tasks.length === 0) { console.log('No scheduled tasks.'); break; }
        tasks.forEach(t => console.log(`[${t.id}] ${t.scheduleType}(${t.scheduleValue}) — ${t.status}\n  ${t.prompt.slice(0, 80)}`));
        break;
      }
      if (sub === 'schedule') {
        // tc tasks schedule --type cron|interval|once --value <v> [--context group|isolated] <prompt>
        let scheduleType, scheduleValue, contextMode, prompt;
        const rArgs = [...rest];
        while (rArgs.length) {
          const a = rArgs.shift();
          if (a === '--type') scheduleType = rArgs.shift();
          else if (a === '--value') scheduleValue = rArgs.shift();
          else if (a === '--context') contextMode = rArgs.shift();
          else prompt = a;
        }
        if (!scheduleType || !scheduleValue || !prompt) {
          console.error('Usage: tc tasks schedule --type cron|interval|once --value <v> <prompt>');
          process.exit(1);
        }
        await sdk.scheduleTask({ prompt, scheduleType, scheduleValue, contextMode });
        console.log('Task scheduled.');
        break;
      }
      if (sub === 'pause') {
        const [id] = rest;
        if (!id) { console.error('Usage: tc tasks pause <id>'); process.exit(1); }
        await sdk.pauseTask(id);
        console.log('Task paused.');
        break;
      }
      if (sub === 'resume') {
        const [id] = rest;
        if (!id) { console.error('Usage: tc tasks resume <id>'); process.exit(1); }
        await sdk.resumeTask(id);
        console.log('Task resumed.');
        break;
      }
      if (sub === 'cancel') {
        const [id] = rest;
        if (!id) { console.error('Usage: tc tasks cancel <id>'); process.exit(1); }
        await sdk.cancelTask(id);
        console.log('Task cancelled.');
        break;
      }
      if (sub === 'update') {
        const [id, ...uArgs] = rest;
        if (!id) { console.error('Usage: tc tasks update <id> [--prompt <p>] [--type <t>] [--value <v>]'); process.exit(1); }
        let prompt, scheduleType, scheduleValue;
        const remaining = [...uArgs];
        while (remaining.length) {
          const a = remaining.shift();
          if (a === '--prompt') prompt = remaining.shift();
          else if (a === '--type') scheduleType = remaining.shift();
          else if (a === '--value') scheduleValue = remaining.shift();
        }
        await sdk.updateTask(id, { prompt, scheduleType, scheduleValue });
        console.log('Task updated.');
        break;
      }
      console.error('Unknown tasks subcommand:', sub);
      process.exit(1);
      break;
    }

    // ── send ───────────────────────────────────────────────────
    case 'send': {
      if (!sub) {
        console.error('Usage: tc send <text>\n       tc send file <path> [--caption <text>]\n       tc send voice <text>');
        process.exit(1);
      }
      if (sub === 'file') {
        const [filePath, ...fArgs] = rest;
        if (!filePath) { console.error('Usage: tc send file <path> [--caption <text>]'); process.exit(1); }
        let caption;
        const remaining = [...fArgs];
        while (remaining.length) {
          const a = remaining.shift();
          if (a === '--caption') caption = remaining.shift();
        }
        await sdk.sendFile(filePath, caption);
        console.log('File sent.');
        break;
      }
      if (sub === 'voice') {
        let provider, voice, caption;
        const voiceRestCopy = [...rest];
        const textParts = [];
        let i = 0;
        while (i < voiceRestCopy.length) {
          const a = voiceRestCopy[i];
          if (a === '--provider') { provider = voiceRestCopy[i+1]; i += 2; }
          else if (a === '--voice') { voice = voiceRestCopy[i+1]; i += 2; }
          else if (a === '--caption') { caption = voiceRestCopy[i+1]; i += 2; }
          else { textParts.push(a); i++; }
        }
        const text = textParts.join(' ');
        if (!text) { console.error('Usage: tc send voice <text> [--provider P] [--voice V] [--caption C]'); process.exit(1); }
        // Run TTS locally via edge-tts
        const { execFileSync: execTts } = await import('child_process');
        const { randomBytes } = await import('crypto');
        const os = await import('os');
        const pathMod = await import('path');
        const fsMod = await import('fs');
        const resolvedVoice = voice || process.env.NANOCLAW_TTS_DEFAULT_VOICE || 'en-GB-SoniaNeural';
        const edgeTtsBin = process.env.NANOCLAW_EDGE_TTS_BIN || 'edge-tts';
        const suffix = randomBytes(4).toString('hex');
        const outDir = process.env.NANOCLAW_TTS_OUTBOUND_DIR || pathMod.default.join('/workspace/group/.nanoclaw-outbound/tts');
        fsMod.default.mkdirSync(outDir, { recursive: true });
        const filePath = pathMod.default.join(outDir, 'voice-' + suffix + '.mp3');
        try {
          execTts(edgeTtsBin, ['--text', text, '--voice', resolvedVoice, '--write-media', filePath], { stdio: 'pipe' });
        } catch (e) {
          console.error('edge-tts failed:', e.message);
          process.exit(1);
        }
        await sdk.sendFile(filePath, caption);
        console.log('Voice message sent.');
        break;
      }
      // tc send [--group <jid>] <text>
      let targetJid = null;
      const sendArgs = [sub, ...rest];
      if (sendArgs[0] === '--group') {
        sendArgs.shift();
        targetJid = sendArgs.shift();
      }
      const text = sendArgs.join(' ');
      if (!text) { console.error('Usage: tc send [--group <jid>] <text>'); process.exit(1); }
      if (targetJid) {
        await sdk.sendMessageToGroup(targetJid, text);
      } else {
        await sdk.sendMessage(text);
      }
      console.log('Message sent.');
      break;
    }

    // ── hosting ────────────────────────────────────────────────
    case 'hosting': {
      if (sub === 'info') {
        const info = await sdk.getHostingInfo();
        console.log(JSON.stringify(info, null, 2));
        break;
      }
      console.error('Unknown hosting subcommand:', sub);
      process.exit(1);
      break;
    }

    // ── app ────────────────────────────────────────────────────
    case 'app': {
      if (sub === 'deploy') {
        const [app] = rest;
        if (!app) { console.error('Usage: tc app deploy <app> [--force-rebuild]'); process.exit(1); }
        const forceRebuild = argv.includes("--force-rebuild") || argv.includes("--force");
        await sdk.deployApp(app, { forceRebuild });
        console.log(forceRebuild ? 'Deploy triggered (force rebuild).' : 'Deploy triggered.');
        break;
      }
      if (sub === 'remove') {
        const [app] = rest;
        if (!app) { console.error('Usage: tc app remove <app>'); process.exit(1); }
        await sdk.removeApp(app);
        console.log('Remove triggered.');
        break;
      }
      if (sub === 'stop') {
        const [app] = rest;
        if (!app) { console.error('Usage: tc app stop <app>'); process.exit(1); }
        await sdk.stopApp(app);
        console.log('Stop triggered.');
        break;
      }
      if (sub === 'restart') {
        const [app, ...rArgs] = rest;
        if (!app) { console.error('Usage: tc app restart <app> [--service <svc>]'); process.exit(1); }
        let services = [];
        const remaining = [...rArgs];
        while (remaining.length) {
          const a = remaining.shift();
          if (a === '--service') services.push(remaining.shift());
        }
        const restartResult = await sdk.restartApp(app, services.length ? services : undefined);
        console.log(JSON.stringify(restartResult, null, 2));
        break;
      }
      if (sub === 'logs') {
        const [app, service, ...lArgs] = rest;
        if (!app || !service) { console.error('Usage: tc app logs <app> <service> [--tail N]'); process.exit(1); }
        let tail;
        const remaining = [...lArgs];
        while (remaining.length) {
          const a = remaining.shift();
          if (a === '--tail') tail = parseInt(remaining.shift(), 10);
        }
        const logsResult = await sdk.getAppLogs(app, service, tail);
        console.log(JSON.stringify(logsResult, null, 2));
        break;
      }
      if (sub === 'exec') {
        const [app, service, ...eArgs] = rest;
        if (!app || !service) { console.error('Usage: tc app exec <app> <service> -- <cmd...>'); process.exit(1); }
        const ddIdx = eArgs.indexOf('--');
        const command = ddIdx >= 0 ? eArgs.slice(ddIdx + 1) : eArgs;
        const execResult = await sdk.execInApp(app, service, command);
        console.log(JSON.stringify(execResult, null, 2));
        break;
      }
      if (sub === 'volumes') {
        const [app, vsub, volume] = rest;
        if (!app) { console.error('Usage: tc app volumes <app>\n       tc app volumes remove <app> <volume>'); process.exit(1); }
        if (app === 'remove') {
          // tc app volumes remove <app> <volume>
          const [rapp, rvol] = [vsub, volume];
          if (!rapp || !rvol) { console.error('Usage: tc app volumes remove <app> <volume>'); process.exit(1); }
          await sdk.removeAppVolume(rapp, rvol);
          console.log('Volume remove triggered.');
        } else {
          const volResult = await sdk.listAppVolumes(app);
          console.log(JSON.stringify(volResult, null, 2));
        }
        break;
      }
      if (sub === 'status') {
        const [app] = rest;
        const statuses = await sdk.getAppStatus(app);
        if (statuses.length === 0) { console.log('No app status available.'); break; }
        statuses.forEach(s => console.log(JSON.stringify(s, null, 2)));
        break;
      }
      if (sub === 'errors') {
        let limit = 5;
        const remaining = [...rest];
        while (remaining.length) {
          const a = remaining.shift();
          if (a === '--limit') limit = parseInt(remaining.shift(), 10);
        }
        const errors = await sdk.getDeployErrors(limit);
        if (errors.length === 0) { console.log('No deploy errors.'); break; }
        errors.forEach(e => console.log(JSON.stringify(e, null, 2)));
        break;
      }
      if (sub === 'wait') {
        const [app, ...wArgs] = rest;
        if (!app) { console.error('Usage: tc app wait <app> [--timeout N]'); process.exit(1); }
        let timeout;
        const remaining = [...wArgs];
        while (remaining.length) {
          const a = remaining.shift();
          if (a === '--timeout') timeout = parseInt(remaining.shift(), 10);
        }
        const waitResult = await sdk.waitForDeploy(app, timeout);
        console.log(JSON.stringify(waitResult, null, 2));
        break;
      }
      if (sub === 'ports') {
        const occupancy = await sdk.getPortOccupancy();
        if (occupancy.length === 0) { console.log('No port allocations found.'); break; }
        const portRange = (await sdk.getHostingInfo()).portRange;
        if (portRange?.env) console.log(`Tenant port range: ${portRange.env}\n`);
        for (const p of occupancy) {
          const declared = p.declaredBy ?? '(undeclared)';
          const container = p.container ? `${p.container.name} [${p.container.status}]` : '(none)';
          const flag = p.conflict ? ' ⚠ CONFLICT' : p.container && !p.declaredBy ? ' ⚠ ZOMBIE' : '';
          console.log(`  :${p.port}  declared=${declared}  container=${container}${flag}`);
        }
        break;
      }
      console.error('Unknown app subcommand:', sub);
      process.exit(1);
      break;
    }

    // ── groups ─────────────────────────────────────────────────
    case 'groups': {
      if (!sub || sub === 'list') {
        const { readFile } = await import('node:fs/promises');
        const ipcDir = process.env.NANOCLAW_IPC_DIR || '/workspace/ipc';
        const groupsPath = `${ipcDir}/available_groups.json`;
        try {
          const raw = await readFile(groupsPath, 'utf8');
          const { groups } = JSON.parse(raw);
          if (!groups || groups.length === 0) {
            console.log('No groups found.');
          } else {
            for (const g of groups) {
              console.log(`${g.name.padEnd(30)} ${g.jid}`);
            }
          }
        } catch {
          console.log('Groups not available. (available_groups.json not found)');
        }
        break;
      }
      if (sub === 'register') {
        let jid, name, folder, trigger;
        const remaining = [...rest];
        while (remaining.length) {
          const a = remaining.shift();
          if (a === '--jid') jid = remaining.shift();
          else if (a === '--name') name = remaining.shift();
          else if (a === '--folder') folder = remaining.shift();
          else if (a === '--trigger') trigger = remaining.shift();
        }
        if (!jid || !name || !folder || !trigger) {
          console.error('Usage: tc groups register --jid <j> --name <n> --folder <f> --trigger <t>');
          process.exit(1);
        }
        await sdk.registerGroup({ jid, name, folder, trigger });
        console.log('Group registered.');
        break;
      }
      if (sub === 'settings') {
        let requiresTrigger;
        const remaining = [...rest];
        while (remaining.length) {
          const a = remaining.shift();
          if (a === '--requires-trigger') requiresTrigger = remaining.shift() !== 'false';
        }
        if (requiresTrigger === undefined) {
          // Read-only: display current settings
          const { readFile } = await import('node:fs/promises');
          const ipcDir = process.env.NANOCLAW_IPC_DIR || '/workspace/ipc';
          const settingsPath = `${ipcDir}/group_settings.json`;
          try {
            const raw = await readFile(settingsPath, 'utf8');
            const s = JSON.parse(raw);
            console.log('requires-trigger:', s.requiresTrigger);
          } catch {
            console.log('Settings not yet written. Use --requires-trigger true|false to set.');
          }
        } else {
          await sdk.updateGroupSettings({ requiresTrigger });
          console.log('Settings updated.');
        }
        break;
      }
      console.error('Unknown groups subcommand:', sub);
      process.exit(1);
      break;
    }

    // ── runtime ────────────────────────────────────────────────
    case 'runtime': {
      if (sub === 'prune') {
        const [scope] = rest;
        if (!scope) { console.error('Usage: tc runtime prune builder|images|images-all|volumes|all'); process.exit(1); }
        const pruneResult = await sdk.pruneRuntime(scope);
        console.log(JSON.stringify(pruneResult, null, 2));
        break;
      }
      if (sub === 'disk') {
        const diskResult = await sdk.getDiskUsage();
        console.log(JSON.stringify(diskResult, null, 2));
        break;
      }
      if (sub === 'reset-buildkit') {
        const bkResult = await sdk.resetBuildkit();
        console.log(JSON.stringify(bkResult, null, 2));
        break;
      }
      console.error('Unknown runtime subcommand:', sub);
      process.exit(1);
      break;
    }

    // ── proxy ──────────────────────────────────────────────────
    case 'proxy': {
      const info = await sdk.getProxyInfo();
      if (!info) {
        console.error('No proxy available for this tenant.'); process.exit(1);
      } else {
        console.log(info.url);
      }
      break;
    }


    // ── skills ──────────────────────────────────────────────────
    case "skills": {
      const { existsSync, mkdirSync, writeFileSync, readFileSync, rmSync, readdirSync } = await import('node:fs').then(m => m.default || m);
      const { join } = await import('node:path').then(m => m.default || m);

      const PERSISTENT_SKILLS = "/workspace/shared/skills";
      const LIVE_SKILLS = "/home/node/.claude/skills";
      const SKILL_FILENAME = "SKILL.md";

      function writeSkill(name, skillContent) {
        for (const base of [PERSISTENT_SKILLS, LIVE_SKILLS]) {
          const dir = join(base, name);
          mkdirSync(dir, { recursive: true });
          writeFileSync(join(dir, SKILL_FILENAME), skillContent, "utf8");
        }
      }

      function deleteSkill(name) {
        for (const base of [PERSISTENT_SKILLS, LIVE_SKILLS]) {
          const dir = join(base, name);
          if (existsSync(dir)) rmSync(dir, { recursive: true });
        }
      }

      function listSkills() {
        if (!existsSync(PERSISTENT_SKILLS)) return [];
        return readdirSync(PERSISTENT_SKILLS, { withFileTypes: true })
          .filter(e => e.isDirectory() && existsSync(join(PERSISTENT_SKILLS, e.name, SKILL_FILENAME)))
          .map(e => {
            const text = readFileSync(join(PERSISTENT_SKILLS, e.name, SKILL_FILENAME), "utf8");
            const textLines = text.split("\n");
            const nameLine = textLines.find(l => l.startsWith("name:")) || "";
            const skillName = nameLine.slice(5).trim() || e.name;
            const descLine = textLines.find(l => l.startsWith("description:")) || "";
            const desc = descLine.slice(12).trim().replace(/^"|"$/g, "");
            return { dir: e.name, skillName, desc };
          });
      }

      if (!sub || sub === "list") {
        const skills = listSkills();
        if (skills.length === 0) { console.log("No tenant skills."); break; }
        skills.forEach(s => console.log(s.dir + (s.desc ? "  — " + s.desc.slice(0, 80) : "")));
        break;
      }

      if (sub === "create") {
        const [name, ...descParts] = rest;
        if (!name) { console.error("Usage: tc skills create <name> [description]"); process.exit(1); }
        const desc = descParts.join(" ") || "";
        const skillContent = "---\nname: " + name + "\ndescription: " + desc + "\n---\n";
        writeSkill(name, skillContent);
        console.log("Skill " + name + " created.");
        break;
      }

      if (sub === "write") {
        const [name] = rest;
        if (!name) { console.error("Usage: tc skills write <name> --content <text>"); process.exit(1); }
        const cidx = rest.indexOf("--content");
        const skillContent = cidx >= 0 ? rest.slice(cidx + 1).join(" ") : "";
        if (!skillContent) { console.error("Provide --content <text>"); process.exit(1); }
        writeSkill(name, skillContent);
        console.log("Skill " + name + " written.");
        break;
      }

      if (sub === "delete" || sub === "remove") {
        const [name] = rest;
        if (!name) { console.error("Usage: tc skills " + sub + " <name>"); process.exit(1); }
        deleteSkill(name);
        console.log("Skill " + name + " deleted.");
        break;
      }

      console.error("Usage: tc skills [list]\n       tc skills create <name> [description]\n       tc skills write <name> --content <text>\n       tc skills delete <name>");
      process.exit(1);
      break;
    }


    // ── whoami ─────────────────────────────────────────────────
    case 'whoami': {
      const ctx = sdk.getContext();
      console.log(ctx.tenantId);
      break;
    }

    case 'memory': {
      // tc memory search <query>           — hybrid search (default, recommended)
      // tc memory search --semantic <q>   — semantic/embedding search only
      // tc memory search --match <q>      — keyword/text search only
      // tc memory describe [id]           — show LCM DB stats or expand a summary node
      if (sub === 'search') {
        const hasFlag = (flag) => { const i = rest.indexOf(flag); if (i !== -1) { rest.splice(i, 1); return true; } return false; };
        const isSemantic = hasFlag('--semantic');
        const isMatch = hasFlag('--match');
        const query = rest.join(' ');
        if (!query) { console.error('Usage: tc memory search [--semantic|--match] <query>'); process.exit(1); }
        if (isSemantic) {
          const result = await sdk.lcmSemanticSearch(query);
          console.log(JSON.stringify(result, null, 2));
        } else if (isMatch) {
          const result = await sdk.lcmSearch(query);
          console.log(JSON.stringify(result, null, 2));
        } else {
          // Default: hybrid (RRF merge of keyword + semantic)
          const result = await sdk.lcmHybridSearch(query);
          console.log(JSON.stringify(result, null, 2));
        }
      } else if (!sub || sub === 'describe') {
        const id = rest[0];
        const result = await sdk.lcmDescribe(id);
        console.log(JSON.stringify(result, null, 2));
      } else {
        console.error(`Unknown memory subcommand: ${sub}`);
        process.exit(1);
      }
      break;
    }

    case undefined:
    case 'help':
    case '--help':
    case '-h': {
      console.log(`tc — Treehouse CLI

Commands:
  tc skills [list]                        List your custom skills
  tc skills create <name> [description]   Create a new skill
  tc skills write <name> --content <text> Write full SKILL.md content
  tc skills delete <name>                 Delete a custom skill

  tc whoami                               Show current tenant ID

  tc memory search <query>               Search LCM memory (hybrid keyword+semantic, default)
  tc memory search --semantic <query>     Semantic/embedding search only
  tc memory search --match <query>        Keyword/text search only
  tc memory describe [id]                 Show LCM DB stats or expand a summary node

  tc app deploy <app> [--force-rebuild]          Deploy an app (--force-rebuild triggers full image rebuild)
  tc app ports                                    Show port occupancy for all apps in this tenant
  tc app remove <app>                     Remove an app
  tc app stop <app>                       Stop an app
  tc app restart <app> [--service <svc>]  Restart an app
  tc app logs <app> <svc> [--tail N]      Fetch app logs
  tc app exec <app> <svc> -- <cmd...>     Exec in app container
  tc app volumes <app>                    List app volumes
  tc app volumes remove <app> <vol>       Remove a named volume
  tc app wait <app> [--timeout N]         Wait for deploy to complete
  tc app status [<app>]                   Show app deploy status
  tc app errors [--limit N]              Show recent deploy errors

  tc proxy                                Show residential proxy URL (if available)

  tc hosting info                         Show hosting info

  tc send <text>                          Send a message to the current group
  tc send --group <jid> <text>            Send a message to a specific group by JID
  tc send file <path> [--caption <t>]     Send a file
  tc send voice <text>                    Send a voice message

  tc tasks                                List scheduled tasks
  tc tasks schedule --type T --value V P  Schedule a task
  tc tasks pause <id>                     Pause a task
  tc tasks resume <id>                    Resume a task
  tc tasks cancel <id>                    Cancel a task
  tc tasks update <id> [opts]             Update a task

  tc groups list                                               List registered groups and their JIDs
  tc groups register --jid J --name N --folder F --trigger T  Register group
  tc groups settings                                           Show current group settings
  tc groups settings --requires-trigger true|false            Update requires-trigger setting

  tc runtime prune <scope>                Prune runtime
  tc runtime disk                         Show disk usage
  tc runtime reset-buildkit               Reset buildkit

  tc hooks [status]                       Show hooks token and enabled state
  tc hooks enable                         Enable hooks (auto-generates token)
  tc hooks disable                        Disable hooks
  tc hooks rotate                         Rotate the hooks bearer token

  tc report <text>                        Send a bug report to the platform admin

  tc creds [list]                         List credentials
  tc creds get <name>                     Get credential value
  tc creds set <name> <value>             Set or update a credential
  tc creds remove <name>                  Remove a credential
`);
      break;
    }

    case 'report': {
      const text = [sub, ...rest].filter(Boolean).join(' ');
      if (!text || text.startsWith('--')) { console.error('Usage: tc report <text>'); process.exit(1); }
      await sdk.sendReport(text);
      console.log('Report sent.');
      break;
    }


    case 'hooks': {
      if (!sub || sub === 'status') {
        const cfg = await sdk.getHooksConfig();
        console.log(`Hooks enabled: ${cfg.hooksEnabled}`);
        console.log(`Hooks token:   ${cfg.hooksToken ?? '(none)'}`);
        break;
      }
      if (sub === 'enable') {
        const cfg = await sdk.setHooksEnabled(true);
        console.log(`Hooks enabled. Token: ${cfg.hooksToken}`);
        break;
      }
      if (sub === 'disable') {
        const cfg = await sdk.setHooksEnabled(false);
        console.log(`Hooks disabled. Token preserved: ${cfg.hooksToken}`);
        break;
      }
      if (sub === 'rotate') {
        const cfg = await sdk.rotateHooksToken();
        console.log(`Token rotated. New token: ${cfg.hooksToken}`);
        break;
      }
      console.error('Usage: tc hooks [status|enable|disable|rotate]');
      process.exit(1);
      break;
    }

    default:
      console.error(`Unknown command: ${command}\nRun "tc help" for usage.`);
      process.exit(1);
  }
}

main().catch(err => {
  console.error('Error:', err.message);
  process.exit(1);
});
