#!/usr/bin/env node
/**
 * plgd — Standalone CLI for connecting to a plgd tenant.
 *
 * Usage:
 *   plgd login                Begin device-flow auth (default server: https://plgd.ai)
 *   plgd login --server URL   Use a non-default server (e.g. http://localhost:3000)
 *   plgd whoami               Print the active tenant + key prefix
 *   plgd logout               Remove the saved config
 *
 * No npm dependencies. Standard library only — runnable via:
 *   npx -y https://plgd.ai/cli/plgd.mjs login
 *
 * Config: ~/.plgd/config.json — JSON of { server, tenantId, key, keyPrefix, savedAt }.
 */

import { mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';

const DEFAULT_SERVER = process.env.PLGD_SERVER || 'https://plgd.ai';
const CONFIG_DIR = join(homedir(), '.plgd');
const CONFIG_PATH = join(CONFIG_DIR, 'config.json');

function parseArgs(argv) {
  const [, , cmd, ...rest] = argv;
  const flags = {};
  const positional = [];
  for (let i = 0; i < rest.length; i++) {
    const a = rest[i];
    if (a.startsWith('--')) {
      const k = a.slice(2);
      const next = rest[i + 1];
      if (next && !next.startsWith('--')) {
        flags[k] = next;
        i++;
      } else {
        flags[k] = true;
      }
    } else {
      positional.push(a);
    }
  }
  return { cmd, flags, positional };
}

function loadConfig() {
  try {
    return JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
  } catch {
    return null;
  }
}

function saveConfig(cfg) {
  mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
  writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), { mode: 0o600 });
}

async function postJSON(url, body) {
  const res = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body || {}),
  });
  const text = await res.text();
  let data;
  try {
    data = JSON.parse(text);
  } catch {
    data = { raw: text };
  }
  return { status: res.status, data };
}

async function cmdLogin({ flags }) {
  const server = (flags.server || DEFAULT_SERVER).replace(/\/$/, '');
  const clientName = flags['client-name'] || 'plgd-cli';

  process.stdout.write(`Requesting auth from ${server}…\n`);
  const start = await postJSON(`${server}/api/cli/auth/start`, {
    clientName,
    requestedName: flags.name || `${clientName} on ${process.env.USER || 'host'}`,
  });
  if (start.status !== 200 || !start.data.ok) {
    console.error('Failed to start auth:', start.data?.error || start.data);
    process.exit(1);
  }
  const { deviceCode, userCode, verificationUrl, verificationUrlComplete, interval, expiresIn } = start.data;

  console.log('');
  console.log('   Open this URL in your browser:');
  console.log('');
  console.log(`     ${verificationUrlComplete}`);
  console.log('');
  console.log(`   Or visit ${verificationUrl} and enter the code:`);
  console.log('');
  console.log(`     ${userCode}`);
  console.log('');
  console.log(`   Code expires in ${Math.floor(expiresIn / 60)} minutes.`);
  console.log('');

  const intervalMs = Math.max(interval * 1000, 2000);
  const startedAt = Date.now();
  const deadline = startedAt + expiresIn * 1000;
  let lastDot = 0;

  process.stdout.write('   Waiting for approval…');
  while (Date.now() < deadline) {
    await new Promise((r) => setTimeout(r, intervalMs));
    const poll = await postJSON(`${server}/api/cli/auth/poll`, { deviceCode });
    if (poll.status === 429) continue; // slow_down — server forces us to back off
    const { status, key, tenantId } = poll.data || {};
    if (status === 'pending') {
      if (Date.now() - lastDot > 4000) {
        process.stdout.write('.');
        lastDot = Date.now();
      }
      continue;
    }
    if (status === 'denied') {
      console.log('\n   Denied. Run `plgd login` to try again.\n');
      process.exit(1);
    }
    if (status === 'expired') {
      console.log('\n   Expired. Run `plgd login` to start over.\n');
      process.exit(1);
    }
    if (status === 'approved' && key) {
      const keyPrefix = key.slice(0, 12);
      saveConfig({
        server,
        tenantId,
        key,
        keyPrefix,
        savedAt: new Date().toISOString(),
      });
      console.log('\n   Authorized.');
      console.log(`   Tenant: ${tenantId}`);
      console.log(`   Key:    ${keyPrefix}…  (saved to ~/.plgd/config.json)`);
      console.log('');
      return;
    }
    console.error(`\n   Unexpected status: ${JSON.stringify(poll.data)}`);
    process.exit(1);
  }
  console.log('\n   Timed out waiting for approval.\n');
  process.exit(1);
}

function cmdWhoami() {
  const cfg = loadConfig();
  if (!cfg) {
    console.log('Not logged in. Run `plgd login` to authorize.');
    process.exit(1);
  }
  console.log(`Server:  ${cfg.server}`);
  console.log(`Tenant:  ${cfg.tenantId}`);
  console.log(`Key:     ${cfg.keyPrefix}…`);
  console.log(`Saved:   ${cfg.savedAt}`);
}

function cmdLogout() {
  if (!existsSync(CONFIG_PATH)) {
    console.log('Not logged in.');
    return;
  }
  rmSync(CONFIG_PATH);
  console.log('Removed ~/.plgd/config.json.');
}

function help() {
  console.log(`plgd — connect a local tool to a plgd tenant

Usage:
  plgd login [--server URL] [--client-name NAME] [--name LABEL]
  plgd whoami
  plgd logout

Env:
  PLGD_SERVER  default server URL (default: https://plgd.ai)

Config is stored at ~/.plgd/config.json (mode 0600).`);
}

const { cmd, flags } = parseArgs(process.argv);
if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') {
  help();
  process.exit(0);
}
const cmds = {
  login: () => cmdLogin({ flags }),
  whoami: cmdWhoami,
  logout: cmdLogout,
};
if (!cmds[cmd]) {
  console.error(`Unknown command: ${cmd}\n`);
  help();
  process.exit(1);
}
await cmds[cmd]();
